File size: 5,715 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7a38a3
 
 
 
 
 
 
 
 
 
1fe7075
 
 
c7a38a3
 
 
 
 
 
 
 
 
 
 
 
 
1fe7075
 
 
c7a38a3
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { exportSPKI, generateKeyPair, SignJWT } from 'jose';
import pg from 'pg';
import request from 'supertest';
import { AppModule } from '../src/app.module.js';
import { setupApp } from '../src/app.setup.js';
import Stripe from 'stripe';
import type { Mock } from 'vitest';
import { ClerkService } from '../src/clerk/clerk.service.js';
import { STRIPE_CLIENT } from '../src/stripe/stripe.constants.js';
import type { ClerkProfile } from '../src/clerk/interfaces/clerk.interface.js';

const ORIGIN = 'http://app.test';
const SECRET = new TextEncoder().encode('test-processing-secret-0123456789abcdef012');
const KID = 'test-key';
const clerkKeys = await generateKeyPair('RS256');
export const otherKeys = await generateKeyPair('RS256');

// Networkless Clerk verification with a test key (CLERK_JWT_KEY in production).
process.env.CLERK_JWT_KEY = await exportSPKI(clerkKeys.publicKey);

export const clerkUsers = new Map<string, ClerkProfile>();

/** Stripe in e2e: real webhook signing, stubbed API calls. */
const realStripe = new Stripe('sk_test_fake');
interface StripeStub {
  webhooks: Stripe['webhooks'];
  customers: { create: Mock };
  checkout: { sessions: { create: Mock } };
  billingPortal: { sessions: { create: Mock } };
  subscriptions: { retrieve: Mock };
}

export const stripeStub: StripeStub = {
  webhooks: realStripe.webhooks,
  customers: { create: vi.fn(async () => ({ id: 'cus_e2e' })) },
  checkout: { sessions: { create: vi.fn(async () => ({ url: 'https://checkout.stripe.test/session' })) } },
  billingPortal: { sessions: { create: vi.fn(async () => ({ url: 'https://billing.stripe.test/portal' })) } },
  subscriptions: { retrieve: vi.fn() },
};

export function signedStripeEvent(type: string, object: object) {
  const payload = JSON.stringify({ id: `evt_${Date.now()}`, object: 'event', type, data: { object } });
  return { payload, signature: realStripe.webhooks.generateTestHeaderString({ payload, secret: 'whsec_test_secret' }) };
}

export async function sessionToken(
  sub: string,
  { key = clerkKeys.privateKey, azp = ORIGIN, expiresIn = 60, sid = 'sess_1' }: { key?: CryptoKey; azp?: string; expiresIn?: number; sid?: string } = {},
) {
  const now = Math.floor(Date.now() / 1000);
  return new SignJWT({ sid, azp })
    .setProtectedHeader({ alg: 'RS256', kid: KID })
    .setIssuer('https://clerk.app.test')
    .setSubject(sub)
    .setIssuedAt(now - 5)
    .setNotBefore(now - 5)
    .setExpirationTime(now + expiresIn)
    .sign(key);
}

/** Headers of a signed-in Clerk user that the fake Clerk backend knows. */
export async function signIn(clerkId: string, email = `${clerkId}@example.com`, name: string | null = 'Test Person') {
  clerkUsers.set(clerkId, { email, name });
  return { Authorization: `Bearer ${await sessionToken(clerkId)}`, Origin: ORIGIN };
}

export async function internalToken(audience = 'prevision-internal', expiresIn = 60) {
  const now = Math.floor(Date.now() / 1000);
  return new SignJWT({}).setProtectedHeader({ alg: 'HS256' }).setAudience(audience).setIssuedAt(now).setExpirationTime(now + expiresIn).sign(SECRET);
}

export async function createApp(): Promise<INestApplication> {
  const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
    .overrideProvider(ClerkService)
    .useFactory({
      factory: (config) => {
        const service = new ClerkService(config);
        service.getVerifiedProfile = async (id: string) => {
          const profile = clerkUsers.get(id);
          if (!profile) throw new Error(`unknown Clerk user ${id}`);
          return profile;
        };
        return service;
      },
      inject: [(await import('../src/config/app-config.js')).APP_CONFIG],
    })
    .overrideProvider(STRIPE_CLIENT)
    .useValue(stripeStub)
    .compile();
  const app = setupApp(moduleRef.createNestApplication({ logger: false, rawBody: true }));
  await app.listen(0);
  return app;
}

export const api = (app: INestApplication) => request(app.getHttpServer());

export async function sql(query: string, values: unknown[] = []) {
  const db = new pg.Client({ connectionString: process.env.PREVISION_DATABASE_URL });
  await db.connect();
  try {
    return (await db.query(query, values)).rows;
  } finally {
    await db.end();
  }
}

export async function resetDatabase() {
  await sql('TRUNCATE subscriptions, generations, users, tiles CASCADE');
  clerkUsers.clear();
}

export async function insertTiles(
  ...tiles: {
    slug: string;
    name: string;
    surfaces?: string[];
    deleted?: boolean;
    collection?: string;
    visibility?: 'public' | 'admin';
    brand?: string;
    organization?: string;
  }[]
) {
  for (const tile of tiles) {
    await sql(
      `INSERT INTO tiles (id, slug, name, surfaces, image_url, deleted_at, collection, visibility, brand, organization, render, updated_at)
       VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, $6, $7, $8, $9, '{"layout": "grid"}', now())`,
      [
        tile.slug,
        tile.name,
        tile.surfaces ?? ['floor'],
        `https://cdn.test/${tile.slug}.jpg`,
        tile.deleted ? new Date() : null,
        tile.collection ?? null,
        tile.visibility ?? 'public',
        tile.brand ?? null,
        tile.organization ?? null,
      ],
    );
  }
}

/** Headers of a signed-in user whose account has role=admin. */
export async function signInAdmin(clerkId: string, app: INestApplication) {
  const headers = await signIn(clerkId);
  await request(app.getHttpServer()).get('/api/me').set(headers);
  await sql('UPDATE users SET role = $1 WHERE clerk_user_id = $2', ['admin', clerkId]);
  return headers;
}