ras-stack 3.2.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +11 -10
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/auth/index.js +1 -1
  4. package/dist/auth/index.js.map +1 -1
  5. package/dist/conformance/index.d.ts +0 -57
  6. package/dist/conformance/index.js +1 -257
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/database/postgres.d.ts +0 -5
  9. package/dist/database/postgres.js +0 -34
  10. package/dist/database/postgres.js.map +1 -1
  11. package/dist/database/sqlite.d.ts +0 -3
  12. package/dist/database/sqlite.js +1 -22
  13. package/dist/database/sqlite.js.map +1 -1
  14. package/dist/email/index.d.ts +0 -11
  15. package/dist/email/index.js +6 -9
  16. package/dist/email/index.js.map +1 -1
  17. package/dist/posthog/client.d.ts +0 -6
  18. package/dist/posthog/client.js +1 -11
  19. package/dist/posthog/client.js.map +1 -1
  20. package/dist/posthog/config.d.ts +1 -0
  21. package/dist/posthog/config.js +2 -0
  22. package/dist/posthog/config.js.map +1 -1
  23. package/dist/posthog/index.d.ts +2 -2
  24. package/dist/posthog/index.js +2 -2
  25. package/dist/posthog/index.js.map +1 -1
  26. package/dist/posthog/proxy.d.ts +0 -1
  27. package/dist/posthog/proxy.js +1 -3
  28. package/dist/posthog/proxy.js.map +1 -1
  29. package/dist/posthog/react.d.ts +1 -2
  30. package/dist/posthog/react.js +1 -2
  31. package/dist/posthog/react.js.map +1 -1
  32. package/dist/posthog/request.d.ts +0 -3
  33. package/dist/posthog/request.js +3 -3
  34. package/dist/posthog/request.js.map +1 -1
  35. package/dist/posthog/server.d.ts +1 -3
  36. package/dist/posthog/server.js +2 -2
  37. package/dist/posthog/server.js.map +1 -1
  38. package/dist/preview/cloudflare.js +1 -1
  39. package/dist/preview/cloudflare.js.map +1 -1
  40. package/dist/preview/dokploy-cli.js +1 -1
  41. package/dist/preview/dokploy-cli.js.map +1 -1
  42. package/dist/preview/dokploy-preview.d.ts +102 -0
  43. package/dist/preview/dokploy-preview.js +377 -0
  44. package/dist/preview/dokploy-preview.js.map +1 -0
  45. package/dist/preview/dokploy.d.ts +2 -102
  46. package/dist/preview/dokploy.js +1 -376
  47. package/dist/preview/dokploy.js.map +1 -1
  48. package/dist/preview/github.js +1 -1
  49. package/dist/preview/github.js.map +1 -1
  50. package/dist/realtime/client.d.ts +1 -11
  51. package/dist/realtime/client.js +2 -98
  52. package/dist/realtime/client.js.map +1 -1
  53. package/dist/realtime/index.d.ts +0 -2
  54. package/dist/realtime/index.js +0 -1
  55. package/dist/realtime/index.js.map +1 -1
  56. package/dist/realtime/react.d.ts +1 -4
  57. package/dist/realtime/react.js +22 -26
  58. package/dist/realtime/react.js.map +1 -1
  59. package/dist/runtime/index.d.ts +2 -64
  60. package/dist/runtime/index.js +1 -255
  61. package/dist/runtime/index.js.map +1 -1
  62. package/dist/runtime/stack.d.ts +64 -0
  63. package/dist/runtime/stack.js +252 -0
  64. package/dist/runtime/stack.js.map +1 -0
  65. package/dist/server/errors.d.ts +0 -22
  66. package/dist/server/errors.js +0 -44
  67. package/dist/server/errors.js.map +1 -1
  68. package/dist/server/health.d.ts +7 -4
  69. package/dist/server/health.js +3 -7
  70. package/dist/server/health.js.map +1 -1
  71. package/dist/server/index.d.ts +2 -10
  72. package/dist/server/index.js +1 -5
  73. package/dist/server/index.js.map +1 -1
  74. package/dist/spacetime/index.d.ts +32 -0
  75. package/dist/spacetime/index.js +93 -0
  76. package/dist/spacetime/index.js.map +1 -0
  77. package/dist/tanstack/middleware.d.ts +0 -1
  78. package/dist/tanstack/middleware.js +2 -5
  79. package/dist/tanstack/middleware.js.map +1 -1
  80. package/dist/tanstack/server.d.ts +2 -11
  81. package/dist/tanstack/server.js +2 -6
  82. package/dist/tanstack/server.js.map +1 -1
  83. package/dist/uploads/index.d.ts +0 -6
  84. package/dist/uploads/index.js +0 -25
  85. package/dist/uploads/index.js.map +1 -1
  86. package/package.json +6 -18
  87. package/dist/server/rate-limit.d.ts +0 -30
  88. package/dist/server/rate-limit.js +0 -73
  89. package/dist/server/rate-limit.js.map +0 -1
package/README.md CHANGED
@@ -30,16 +30,17 @@ An application can use one surface without adopting the others. The npm package
30
30
 
31
31
  ## The stack 🧰
32
32
 
33
- | Layer | Supported technology | What `ras-stack` centralizes |
34
- | ------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
35
- | Runtime and tooling | Node, ESM TypeScript, pnpm, Just, Oxlint | Setup actions and version synchronization |
36
- | Web application | TanStack Start, React | Request binding, mutation-origin checks, canonical hosts, health handlers |
37
- | Authentication | Better Auth | Secure option builders, origins, secrets, redirects, failure classification, and React action state |
38
- | Data | Drizzle, `better-sqlite3`, libsql, Postgres.js | Connection lifecycle, safety defaults, migrations, target selection, and conformance checks |
39
- | Realtime | Centrifuge, Centrifugo, Caddy | Publishing, tokens, browser/React lifecycle, presence, proxy configuration, binaries, and supervision |
40
- | Email and uploads | Nodemailer 9/10, `tus-js-client` | SMTP configuration/delivery, auth callbacks, and promise-based resumable uploads |
41
- | Observability | PostHog JS, React, Node, and OpenTelemetry | Analytics, replay, errors, logs, metrics, tracing, correlation, proxying, and shutdown |
42
- | Delivery | GitHub Actions, Changesets, Dokploy, Docker | Checks, releases, preview lifecycle/status, production assets, and runtime binaries |
33
+ | Layer | Supported technology | What `ras-stack` centralizes |
34
+ | ------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------- |
35
+ | Runtime and tooling | Node, ESM TypeScript, pnpm, Just, Oxlint | Setup actions and version synchronization |
36
+ | Web application | TanStack Start, React | Request binding, mutation-origin checks, canonical hosts, health handlers |
37
+ | Authentication | Better Auth | Secure option builders, origins, secrets, redirects, failure classification, and React action state |
38
+ | Data | Drizzle, `better-sqlite3`, libsql, Postgres.js | Connection lifecycle, safety defaults, migrations, target selection, and conformance checks |
39
+ | Realtime | Centrifuge, Centrifugo, Caddy | Publishing, tokens, browser/React lifecycle, proxy configuration, binaries, and supervision |
40
+ | Realtime database | SpacetimeDB | Server calls, migration-planned module publishing, environment headers, and binding checks |
41
+ | Email and uploads | Nodemailer 9/10, `tus-js-client` | SMTP configuration/delivery, auth callbacks, and promise-based resumable uploads |
42
+ | Observability | PostHog JS, React, Node, and OpenTelemetry | Analytics, replay, errors, logs, metrics, tracing, correlation, proxying, and shutdown |
43
+ | Delivery | GitHub Actions, Changesets, Dokploy, Docker | Checks, releases, preview lifecycle/status, production assets, and runtime binaries |
43
44
 
44
45
  Applications still configure every upstream library directly. This table describes what is tested together, not a replacement API.
45
46
 
@@ -1,4 +1,4 @@
1
- export { acceptedOrigins, forwardedOrigin, parseOrigin, publicOrigin, requireSameOrigin, trustedOrigins, validSameOriginRequest, } from './origins.js';
1
+ export { forwardedOrigin, parseOrigin, publicOrigin, trustedOrigins, validSameOriginRequest } from './origins.js';
2
2
  export type { OriginOptions } from './origins.js';
3
3
  export { configuredProviderOptions, configuredProviders, providerCredentials } from './providers.js';
4
4
  export type { ProviderCredentials, ProviderEnvironmentOptions } from './providers.js';
@@ -1,4 +1,4 @@
1
- export { acceptedOrigins, forwardedOrigin, parseOrigin, publicOrigin, requireSameOrigin, trustedOrigins, validSameOriginRequest, } from './origins.js';
1
+ export { forwardedOrigin, parseOrigin, publicOrigin, trustedOrigins, validSameOriginRequest } from './origins.js';
2
2
  export { configuredProviderOptions, configuredProviders, providerCredentials } from './providers.js';
3
3
  export { randomId, randomToken } from './random.js';
4
4
  export { persistedSecret } from './secret.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,EACf,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,sBAAsB,GACvB,MAAM,cAAc,CAAA;AAErB,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AAEpG,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7C,OAAO,EAAE,sBAAsB,EAAE,+BAA+B,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA","sourcesContent":["export {\n acceptedOrigins,\n forwardedOrigin,\n parseOrigin,\n publicOrigin,\n requireSameOrigin,\n trustedOrigins,\n validSameOriginRequest,\n} from './origins.js'\nexport type { OriginOptions } from './origins.js'\nexport { configuredProviderOptions, configuredProviders, providerCredentials } from './providers.js'\nexport type { ProviderCredentials, ProviderEnvironmentOptions } from './providers.js'\nexport { randomId, randomToken } from './random.js'\nexport { persistedSecret } from './secret.js'\nexport type { PersistedSecretOptions } from './secret.js'\nexport { standardAccountOptions, standardEmailAndPasswordOptions, standardRateLimitOptions, standardSessionOptions } from './settings.js'\nexport type { RateLimitRule, SessionOptions, StandardAccountOptions, StandardEmailAndPasswordOptions } from './settings.js'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,YAAY,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAA;AAEjH,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AAEpG,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7C,OAAO,EAAE,sBAAsB,EAAE,+BAA+B,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA","sourcesContent":["export { forwardedOrigin, parseOrigin, publicOrigin, trustedOrigins, validSameOriginRequest } from './origins.js'\nexport type { OriginOptions } from './origins.js'\nexport { configuredProviderOptions, configuredProviders, providerCredentials } from './providers.js'\nexport type { ProviderCredentials, ProviderEnvironmentOptions } from './providers.js'\nexport { randomId, randomToken } from './random.js'\nexport { persistedSecret } from './secret.js'\nexport type { PersistedSecretOptions } from './secret.js'\nexport { standardAccountOptions, standardEmailAndPasswordOptions, standardRateLimitOptions, standardSessionOptions } from './settings.js'\nexport type { RateLimitRule, SessionOptions, StandardAccountOptions, StandardEmailAndPasswordOptions } from './settings.js'\n"]}
@@ -1,52 +1,8 @@
1
- export declare class ConformanceError extends Error {
2
- readonly scenario: string;
3
- constructor(scenario: string, message: string, options?: {
4
- cause?: unknown;
5
- });
6
- }
7
1
  export declare function assertMutationOriginConformance(guard: (request: Request) => void | Promise<void>, options?: {
8
2
  trustForwardedHeaders?: boolean;
9
3
  }): Promise<void>;
10
- export type HealthHandlerFactory = (check: () => void | Promise<void>) => () => Response | Promise<Response>;
11
- export declare function assertHealthHandlerConformance(createHandler: HealthHandlerFactory): Promise<void>;
12
4
  export type SqlitePragmaReader = (name: 'journal_mode' | 'synchronous' | 'busy_timeout' | 'foreign_keys') => unknown;
13
5
  export declare function assertSqliteConformance(readPragma: SqlitePragmaReader): Promise<void>;
14
- export type RealtimeTokenSigner = (subject: string, claims: Record<string, unknown>) => string | Promise<string>;
15
- export type RealtimeTokenConformanceOptions = {
16
- secret: string;
17
- maxTtlSeconds?: number;
18
- now?: number;
19
- };
20
- export declare function assertRealtimeTokenConformance(sign: RealtimeTokenSigner, options: RealtimeTokenConformanceOptions): Promise<void>;
21
- export type RateLimitStoreProbe = {
22
- increment: (key: string, windowSeconds: number, now: number) => Promise<{
23
- count: number;
24
- resetAt: number;
25
- }> | {
26
- count: number;
27
- resetAt: number;
28
- };
29
- };
30
- export declare function assertRateLimitStoreConformance(store: RateLimitStoreProbe, options?: {
31
- now?: number;
32
- }): Promise<void>;
33
- export type AuthSecretProvider = (environment: NodeJS.ProcessEnv) => string | Promise<string>;
34
- export declare function assertAuthSecretConformance(secret: AuthSecretProvider, options?: {
35
- environmentKey?: string;
36
- }): Promise<void>;
37
- export type RealtimePublisherProbe = {
38
- publish: (channel: string, data: unknown) => boolean;
39
- close: () => Promise<void>;
40
- };
41
- export declare function assertRealtimePublisherConformance(create: () => RealtimePublisherProbe, options?: {
42
- probes?: number;
43
- }): Promise<void>;
44
- export type SmtpConfigReader = (environment: NodeJS.ProcessEnv) => {
45
- host: string;
46
- port: number;
47
- from: string;
48
- } | undefined;
49
- export declare function assertSmtpConfigConformance(read: SmtpConfigReader): void;
50
6
  export type DatabaseTarget = {
51
7
  provider: 'sqlite';
52
8
  file: string;
@@ -59,16 +15,3 @@ export type DatabaseTargetResolver = (options: {
59
15
  sqliteFile: string;
60
16
  }) => DatabaseTarget;
61
17
  export declare function assertDatabaseTargetConformance(resolve: DatabaseTargetResolver): void;
62
- export declare function assertPostHogBrowserConformance(options: Record<string, unknown>): void;
63
- type PostHogContextParser = (request: Request, options?: {
64
- authenticatedDistinctId?: string;
65
- allowAnonymousDistinctId?: boolean;
66
- }) => {
67
- distinctId?: string;
68
- sessionId?: string;
69
- properties: {
70
- $session_id?: string;
71
- };
72
- };
73
- export declare function assertPostHogRequestConformance(parse: PostHogContextParser): void;
74
- export {};
@@ -1,4 +1,4 @@
1
- export class ConformanceError extends Error {
1
+ class ConformanceError extends Error {
2
2
  scenario;
3
3
  constructor(scenario, message, options = {}) {
4
4
  super(`${scenario}: ${message}`, options.cause === undefined ? undefined : { cause: options.cause });
@@ -27,33 +27,6 @@ export async function assertMutationOriginConformance(guard, options = {}) {
27
27
  })));
28
28
  }
29
29
  }
30
- export async function assertHealthHandlerConformance(createHandler) {
31
- const healthy = await createHandler(() => undefined)();
32
- if (healthy.status !== 200)
33
- throw new ConformanceError('healthy dependency', `expected status 200, received ${healthy.status}`);
34
- const healthyBody = await responseBody(healthy, 'healthy dependency');
35
- if (healthyBody.ok !== true)
36
- throw new ConformanceError('healthy dependency', 'response body must contain ok: true');
37
- const privateMessage = 'password=private-diagnostic';
38
- const unavailable = await createHandler(() => Promise.reject(new Error(privateMessage)))();
39
- if (unavailable.status !== 503) {
40
- throw new ConformanceError('unavailable dependency', `expected status 503, received ${unavailable.status}`);
41
- }
42
- const unavailableText = await unavailable.text();
43
- if (unavailableText.includes(privateMessage)) {
44
- throw new ConformanceError('unavailable dependency', 'response exposed the private diagnostic message');
45
- }
46
- let unavailableBody;
47
- try {
48
- unavailableBody = JSON.parse(unavailableText);
49
- }
50
- catch (error) {
51
- throw new ConformanceError('unavailable dependency', 'response body must be JSON', { cause: error });
52
- }
53
- if (!unavailableBody || typeof unavailableBody !== 'object' || !('ok' in unavailableBody) || unavailableBody.ok !== false) {
54
- throw new ConformanceError('unavailable dependency', 'response body must contain ok: false');
55
- }
56
- }
57
30
  export async function assertSqliteConformance(readPragma) {
58
31
  const values = {
59
32
  journalMode: String(await readPragma('journal_mode')).toLowerCase(),
@@ -74,162 +47,6 @@ export async function assertSqliteConformance(readPragma) {
74
47
  throw new ConformanceError('SQLite foreign keys', `expected enabled (1), received ${values.foreignKeys}`);
75
48
  }
76
49
  }
77
- export async function assertRealtimeTokenConformance(sign, options) {
78
- const now = options.now ?? Math.floor(Date.now() / 1000);
79
- const maxTtlSeconds = options.maxTtlSeconds ?? 60 * 60;
80
- const token = await sign('person-123', { channel: 'room:1' });
81
- const { header, payload, signed, signature } = decodeToken(token);
82
- if (header.alg !== 'HS256') {
83
- throw new ConformanceError('realtime token algorithm', `expected HS256, received ${JSON.stringify(header.alg)}`);
84
- }
85
- if (payload.sub !== 'person-123') {
86
- throw new ConformanceError('realtime token subject', 'token must bind the subject it was signed for');
87
- }
88
- if (payload.channel !== 'room:1') {
89
- throw new ConformanceError('realtime token claims', 'token must carry the claims it was signed with');
90
- }
91
- if (typeof payload.exp !== 'number') {
92
- throw new ConformanceError('realtime token expiry', 'token must expire');
93
- }
94
- if (payload.exp <= now) {
95
- throw new ConformanceError('realtime token expiry', 'token expired before it was issued');
96
- }
97
- if (payload.exp - now > maxTtlSeconds) {
98
- throw new ConformanceError('realtime token expiry', `token outlives the ${maxTtlSeconds} second maximum`);
99
- }
100
- if (!(await verifyHmac(signed, signature, options.secret))) {
101
- throw new ConformanceError('realtime token signature', 'token is not signed with the shared Centrifugo secret');
102
- }
103
- const other = decodeToken(await sign('person-456', { channel: 'room:1' })).payload;
104
- if (other.sub === payload.sub) {
105
- throw new ConformanceError('realtime token subject', 'every subject received the same identity');
106
- }
107
- }
108
- function decodeToken(token) {
109
- const segments = token.split('.');
110
- if (segments.length !== 3)
111
- throw new ConformanceError('realtime token format', 'expected a three-segment JWT');
112
- const [header, claims, signature] = segments;
113
- return {
114
- header: decodeSegment(header, 'header'),
115
- payload: decodeSegment(claims, 'payload'),
116
- signed: `${header}.${claims}`,
117
- signature,
118
- };
119
- }
120
- function decodeSegment(segment, name) {
121
- try {
122
- const padded = segment
123
- .replaceAll('-', '+')
124
- .replaceAll('_', '/')
125
- .padEnd(Math.ceil(segment.length / 4) * 4, '=');
126
- const value = JSON.parse(atob(padded));
127
- if (value && typeof value === 'object')
128
- return value;
129
- }
130
- catch (error) {
131
- throw new ConformanceError('realtime token format', `${name} is not base64url JSON`, { cause: error });
132
- }
133
- throw new ConformanceError('realtime token format', `${name} is not an object`);
134
- }
135
- async function verifyHmac(signed, signature, secret) {
136
- const encoder = new TextEncoder();
137
- const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
138
- const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(signed)));
139
- const expected = btoa(String.fromCharCode(...digest))
140
- .replaceAll('+', '-')
141
- .replaceAll('/', '_')
142
- .replaceAll('=', '');
143
- return expected === signature;
144
- }
145
- // The package cannot reach a consumer's PostgreSQL, so the store contract travels to wherever the real database is.
146
- export async function assertRateLimitStoreConformance(store, options = {}) {
147
- const now = options.now ?? Math.floor(Date.now() / 1000);
148
- const window = 60;
149
- const key = `conformance:${crypto.randomUUID()}`;
150
- const first = await store.increment(key, window, now);
151
- if (first.count !== 1)
152
- throw new ConformanceError('rate limit store', `expected a new key to start at 1, received ${first.count}`);
153
- if (first.resetAt !== now + window) {
154
- throw new ConformanceError('rate limit store', `expected the window to end at ${now + window}, received ${first.resetAt}`);
155
- }
156
- const second = await store.increment(key, window, now + 1);
157
- if (second.count !== 2)
158
- throw new ConformanceError('rate limit store', `expected the second request to count 2, received ${second.count}`);
159
- if (second.resetAt !== first.resetAt) {
160
- throw new ConformanceError('rate limit store', 'a request inside the window must not extend it');
161
- }
162
- const other = await store.increment(`conformance:${crypto.randomUUID()}`, window, now);
163
- if (other.count !== 1)
164
- throw new ConformanceError('rate limit store', 'one key consumed another key budget');
165
- const expired = await store.increment(key, window, first.resetAt);
166
- if (expired.count !== 1)
167
- throw new ConformanceError('rate limit store', 'an elapsed window must start a new count');
168
- if (expired.resetAt !== first.resetAt + window) {
169
- throw new ConformanceError('rate limit store', 'an elapsed window must start a new window');
170
- }
171
- }
172
- // A secret that changes between restarts signs out every session, and a short one is guessable. Neither shows up
173
- // until it is already in production, so the contract is checked against the provider an application wired.
174
- export async function assertAuthSecretConformance(secret, options = {}) {
175
- const key = options.environmentKey ?? 'AUTH_SECRET';
176
- const configured = 'configured-secret-value-that-is-long-enough';
177
- const first = await secret({});
178
- if (typeof first !== 'string' || !first.trim())
179
- throw new ConformanceError('auth secret', 'provider returned no secret');
180
- if (first.length < 32)
181
- throw new ConformanceError('auth secret', `expected at least 32 characters, received ${first.length}`);
182
- if (new Set(first).size < 8)
183
- throw new ConformanceError('auth secret', 'secret does not look randomly generated');
184
- if ((await secret({})) !== first) {
185
- throw new ConformanceError('auth secret', 'secret changed between calls, which signs out every session on restart');
186
- }
187
- if ((await secret({ [key]: configured })) !== configured) {
188
- throw new ConformanceError('auth secret', `${key} must take precedence over a generated secret`);
189
- }
190
- }
191
- // A publisher that accepts every channel turns a burst into unbounded memory, and one that accepts work after close
192
- // loses publications during shutdown. Both appear only under load.
193
- export async function assertRealtimePublisherConformance(create, options = {}) {
194
- const probes = options.probes ?? 5_000;
195
- const bounded = create();
196
- let admitted = 0;
197
- for (let attempt = 0; attempt < probes; attempt++)
198
- if (bounded.publish(`conformance-${attempt}`, { attempt }))
199
- admitted += 1;
200
- if (admitted === probes)
201
- throw new ConformanceError('realtime publisher', `accepted all ${probes} channels without a capacity limit`);
202
- if (admitted === 0)
203
- throw new ConformanceError('realtime publisher', 'rejected every publication');
204
- await bounded.close();
205
- const closed = create();
206
- await closed.close();
207
- if (closed.publish('conformance', {}))
208
- throw new ConformanceError('realtime publisher', 'accepted work after it was closed');
209
- }
210
- // Half-configured SMTP is the failure that reaches production, because nothing sends mail until something needs to.
211
- export function assertSmtpConfigConformance(read) {
212
- if (read({}) !== undefined)
213
- throw new ConformanceError('SMTP configuration', 'expected no configuration when nothing is set');
214
- const configured = read({ SMTP_HOST: 'smtp.example', EMAIL_FROM: 'app@example.com' });
215
- if (!configured)
216
- throw new ConformanceError('SMTP configuration', 'expected a configuration from a host and sender');
217
- if (configured.port !== 587)
218
- throw new ConformanceError('SMTP configuration', `expected the default port 587, received ${configured.port}`);
219
- rejects(read, { SMTP_HOST: 'smtp.example' }, 'a host without a sender');
220
- rejects(read, { EMAIL_FROM: 'app@example.com' }, 'a sender without a host');
221
- rejects(read, { SMTP_HOST: 'smtp.example', EMAIL_FROM: 'app@example.com', SMTP_PORT: '70000' }, 'a port outside the valid range');
222
- rejects(read, { SMTP_HOST: 'smtp.example', EMAIL_FROM: 'app@example.com', SMTP_USER: 'user' }, 'a user without a password');
223
- }
224
- function rejects(read, environment, scenario) {
225
- try {
226
- read(environment);
227
- }
228
- catch {
229
- return;
230
- }
231
- throw new ConformanceError('SMTP configuration', `expected ${scenario} to be rejected`);
232
- }
233
50
  export function assertDatabaseTargetConformance(resolve) {
234
51
  const sqliteFile = '/data/application.sqlite';
235
52
  const sqlite = resolve({ sqliteFile });
@@ -250,68 +67,6 @@ export function assertDatabaseTargetConformance(resolve) {
250
67
  }
251
68
  throw new ConformanceError('invalid database target', 'expected a non-PostgreSQL URL to be rejected');
252
69
  }
253
- export function assertPostHogBrowserConformance(options) {
254
- if (typeof options.api_host !== 'string' || !options.api_host.trim()) {
255
- throw new ConformanceError('PostHog browser initialization', 'api_host must be configured');
256
- }
257
- if (typeof options.ui_host !== 'string' || !options.ui_host.trim()) {
258
- throw new ConformanceError('PostHog browser initialization', 'ui_host must be configured');
259
- }
260
- if (typeof options.defaults !== 'string' || !options.defaults.trim()) {
261
- throw new ConformanceError('PostHog browser initialization', 'SDK defaults must be pinned');
262
- }
263
- if (!options.capture_exceptions) {
264
- throw new ConformanceError('PostHog browser initialization', 'exception autocapture must be enabled');
265
- }
266
- if (options.capture_pageview !== 'history_change') {
267
- throw new ConformanceError('PostHog browser initialization', 'SPA pageviews must follow history changes');
268
- }
269
- if (options.capture_performance !== true) {
270
- throw new ConformanceError('PostHog browser initialization', 'browser performance capture must be enabled');
271
- }
272
- if (options.person_profiles !== 'identified_only') {
273
- throw new ConformanceError('PostHog browser initialization', 'person profiles must be limited to identified users');
274
- }
275
- if (options.mask_personal_data_properties !== true) {
276
- throw new ConformanceError('PostHog browser initialization', 'personal-data URL properties must be masked');
277
- }
278
- if (!Array.isArray(options.custom_personal_data_properties) || !options.custom_personal_data_properties.includes('token')) {
279
- throw new ConformanceError('PostHog browser initialization', 'token query parameters must be masked');
280
- }
281
- const recording = options.session_recording;
282
- if (!recording || typeof recording !== 'object' || !('maskAllInputs' in recording) || recording.maskAllInputs !== true) {
283
- throw new ConformanceError('PostHog browser initialization', 'session replay must mask all inputs by default');
284
- }
285
- const logs = serviceName(options.logs);
286
- const metrics = serviceName(options.metrics);
287
- if ((logs || metrics) && (!logs || logs !== metrics)) {
288
- throw new ConformanceError('PostHog browser initialization', 'logs and metrics must share one service name');
289
- }
290
- }
291
- function serviceName(value) {
292
- if (!value || typeof value !== 'object' || !('serviceName' in value) || typeof value.serviceName !== 'string')
293
- return undefined;
294
- return value.serviceName.trim() || undefined;
295
- }
296
- export function assertPostHogRequestConformance(parse) {
297
- const matched = parse(postHogRequest('person-123', 'session-456'), { authenticatedDistinctId: 'person-123' });
298
- if (matched.distinctId !== 'person-123' || matched.sessionId !== 'session-456' || matched.properties.$session_id !== 'session-456') {
299
- throw new ConformanceError('authenticated PostHog request', 'expected verified identity and session propagation');
300
- }
301
- const spoofed = parse(postHogRequest('attacker', 'session-456'), { authenticatedDistinctId: 'person-123' });
302
- if (spoofed.distinctId !== undefined) {
303
- throw new ConformanceError('spoofed PostHog request', 'unverified distinct id was trusted');
304
- }
305
- const malformed = parse(postHogRequest('person-123', 'x'.repeat(129)), { authenticatedDistinctId: 'person-123' });
306
- if (malformed.sessionId !== undefined || malformed.properties.$session_id !== undefined) {
307
- throw new ConformanceError('malformed PostHog request', 'unbounded session id was propagated');
308
- }
309
- }
310
- function postHogRequest(distinctId, sessionId) {
311
- return new Request('https://app.example/action', {
312
- headers: { 'x-posthog-distinct-id': distinctId, 'x-posthog-session-id': sessionId },
313
- });
314
- }
315
70
  async function accepted(scenario, work) {
316
71
  try {
317
72
  await work();
@@ -329,15 +84,4 @@ async function rejected(scenario, work) {
329
84
  }
330
85
  throw new ConformanceError(scenario, 'expected request to be rejected');
331
86
  }
332
- async function responseBody(response, scenario) {
333
- try {
334
- const body = await response.json();
335
- if (body && typeof body === 'object')
336
- return body;
337
- }
338
- catch (error) {
339
- throw new ConformanceError(scenario, 'response body must be JSON', { cause: error });
340
- }
341
- throw new ConformanceError(scenario, 'response body must be an object');
342
- }
343
87
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/conformance/index.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAE9B,QAAQ;IADnB,YACW,QAAgB,EACzB,OAAe,EACf,OAAO,GAAwB,EAAE;QAEjC,KAAK,CAAC,GAAG,QAAQ,KAAK,OAAO,EAAE,EAAE,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC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,MAAM,IAAI,EAAE,CAAA;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAM;IACR,CAAC;IACD,MAAM,IAAI,gBAAgB,CAAC,QAAQ,EAAE,iCAAiC,CAAC,CAAA;AACzE,CAAC;AAED,KAAK,UAAU,YAAY,CAAC,QAAkB,EAAE,QAAgB;IAC9D,IAAI,CAAC;QACH,MAAM,IAAI,GAAY,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;QAC3C,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,OAAO,IAA+B,CAAA;IAC9E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,gBAAgB,CAAC,QAAQ,EAAE,4BAA4B,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;IACtF,CAAC;IACD,MAAM,IAAI,gBAAgB,CAAC,QAAQ,EAAE,iCAAiC,CAAC,CAAA;AACzE,CAAC","sourcesContent":["export class ConformanceError extends Error {\n constructor(\n readonly scenario: string,\n message: string,\n options: { cause?: unknown } = {},\n ) {\n super(`${scenario}: ${message}`, options.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'ConformanceError'\n }\n}\n\nexport async function assertMutationOriginConformance(\n guard: (request: Request) => void | Promise<void>,\n options: { trustForwardedHeaders?: boolean } = {},\n) {\n await accepted('same-origin request', () =>\n guard(\n new Request('https://app.example/action', {\n method: 'POST',\n headers: { origin: 'https://app.example', 'sec-fetch-site': 'same-origin' },\n }),\n ),\n )\n await rejected('cross-origin request', () =>\n guard(\n new Request('https://app.example/action', {\n method: 'POST',\n headers: { origin: 'https://attacker.example', 'sec-fetch-site': 'cross-site' },\n }),\n ),\n )\n await rejected('missing-origin request', () => guard(new Request('https://app.example/action', { method: 'POST' })))\n if (!options.trustForwardedHeaders) {\n await rejected('spoofed forwarded-origin request', () =>\n guard(\n new Request('https://app.example/action', {\n method: 'POST',\n headers: {\n origin: 'https://attacker.example',\n 'x-forwarded-host': 'attacker.example',\n 'x-forwarded-proto': 'https',\n },\n }),\n ),\n )\n }\n}\n\nexport type HealthHandlerFactory = (check: () => void | Promise<void>) => () => Response | Promise<Response>\n\nexport async function assertHealthHandlerConformance(createHandler: HealthHandlerFactory) {\n const healthy = await createHandler(() => undefined)()\n if (healthy.status !== 200) throw new ConformanceError('healthy dependency', `expected status 200, received ${healthy.status}`)\n const healthyBody = await responseBody(healthy, 'healthy dependency')\n if (healthyBody.ok !== true) throw new ConformanceError('healthy dependency', 'response body must contain ok: true')\n\n const privateMessage = 'password=private-diagnostic'\n const unavailable = await createHandler(() => Promise.reject(new Error(privateMessage)))()\n if (unavailable.status !== 503) {\n throw new ConformanceError('unavailable dependency', `expected status 503, received ${unavailable.status}`)\n }\n const unavailableText = await unavailable.text()\n if (unavailableText.includes(privateMessage)) {\n throw new ConformanceError('unavailable dependency', 'response exposed the private diagnostic message')\n }\n let unavailableBody: unknown\n try {\n unavailableBody = JSON.parse(unavailableText)\n } catch (error) {\n throw new ConformanceError('unavailable dependency', 'response body must be JSON', { cause: error })\n }\n if (!unavailableBody || typeof unavailableBody !== 'object' || !('ok' in unavailableBody) || unavailableBody.ok !== false) {\n throw new ConformanceError('unavailable dependency', 'response body must contain ok: false')\n }\n}\n\nexport type SqlitePragmaReader = (name: 'journal_mode' | 'synchronous' | 'busy_timeout' | 'foreign_keys') => unknown\n\nexport async function assertSqliteConformance(readPragma: SqlitePragmaReader) {\n const values = {\n journalMode: String(await readPragma('journal_mode')).toLowerCase(),\n synchronous: Number(await readPragma('synchronous')),\n busyTimeout: Number(await readPragma('busy_timeout')),\n foreignKeys: Number(await readPragma('foreign_keys')),\n }\n if (values.journalMode !== 'wal' && values.journalMode !== 'memory') {\n throw new ConformanceError('SQLite journal mode', `expected wal or memory, received ${values.journalMode}`)\n }\n if (values.synchronous !== 2) {\n throw new ConformanceError('SQLite synchronous mode', `expected FULL (2), received ${values.synchronous}`)\n }\n if (values.busyTimeout !== 5000) {\n throw new ConformanceError('SQLite busy timeout', `expected 5000, received ${values.busyTimeout}`)\n }\n if (values.foreignKeys !== 1) {\n throw new ConformanceError('SQLite foreign keys', `expected enabled (1), received ${values.foreignKeys}`)\n }\n}\n\nexport type RealtimeTokenSigner = (subject: string, claims: Record<string, unknown>) => string | Promise<string>\n\nexport type RealtimeTokenConformanceOptions = { secret: string; maxTtlSeconds?: number; now?: number }\n\nexport async function assertRealtimeTokenConformance(sign: RealtimeTokenSigner, options: RealtimeTokenConformanceOptions) {\n const now = options.now ?? Math.floor(Date.now() / 1000)\n const maxTtlSeconds = options.maxTtlSeconds ?? 60 * 60\n const token = await sign('person-123', { channel: 'room:1' })\n const { header, payload, signed, signature } = decodeToken(token)\n\n if (header.alg !== 'HS256') {\n throw new ConformanceError('realtime token algorithm', `expected HS256, received ${JSON.stringify(header.alg)}`)\n }\n if (payload.sub !== 'person-123') {\n throw new ConformanceError('realtime token subject', 'token must bind the subject it was signed for')\n }\n if (payload.channel !== 'room:1') {\n throw new ConformanceError('realtime token claims', 'token must carry the claims it was signed with')\n }\n if (typeof payload.exp !== 'number') {\n throw new ConformanceError('realtime token expiry', 'token must expire')\n }\n if (payload.exp <= now) {\n throw new ConformanceError('realtime token expiry', 'token expired before it was issued')\n }\n if (payload.exp - now > maxTtlSeconds) {\n throw new ConformanceError('realtime token expiry', `token outlives the ${maxTtlSeconds} second maximum`)\n }\n if (!(await verifyHmac(signed, signature, options.secret))) {\n throw new ConformanceError('realtime token signature', 'token is not signed with the shared Centrifugo secret')\n }\n\n const other = decodeToken(await sign('person-456', { channel: 'room:1' })).payload\n if (other.sub === payload.sub) {\n throw new ConformanceError('realtime token subject', 'every subject received the same identity')\n }\n}\n\nfunction decodeToken(token: string) {\n const segments = token.split('.')\n if (segments.length !== 3) throw new ConformanceError('realtime token format', 'expected a three-segment JWT')\n const [header, claims, signature] = segments as [string, string, string]\n return {\n header: decodeSegment(header, 'header'),\n payload: decodeSegment(claims, 'payload'),\n signed: `${header}.${claims}`,\n signature,\n }\n}\n\nfunction decodeSegment(segment: string, name: string): Record<string, unknown> {\n try {\n const padded = segment\n .replaceAll('-', '+')\n .replaceAll('_', '/')\n .padEnd(Math.ceil(segment.length / 4) * 4, '=')\n const value: unknown = JSON.parse(atob(padded))\n if (value && typeof value === 'object') return value as Record<string, unknown>\n } catch (error) {\n throw new ConformanceError('realtime token format', `${name} is not base64url JSON`, { cause: error })\n }\n throw new ConformanceError('realtime token format', `${name} is not an object`)\n}\n\nasync function verifyHmac(signed: string, signature: string, secret: string) {\n const encoder = new TextEncoder()\n const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(signed)))\n const expected = btoa(String.fromCharCode(...digest))\n .replaceAll('+', '-')\n .replaceAll('/', '_')\n .replaceAll('=', '')\n return expected === signature\n}\n\nexport type RateLimitStoreProbe = {\n increment: (\n key: string,\n windowSeconds: number,\n now: number,\n ) => Promise<{ count: number; resetAt: number }> | { count: number; resetAt: number }\n}\n\n// The package cannot reach a consumer's PostgreSQL, so the store contract travels to wherever the real database is.\nexport async function assertRateLimitStoreConformance(store: RateLimitStoreProbe, options: { now?: number } = {}) {\n const now = options.now ?? Math.floor(Date.now() / 1000)\n const window = 60\n const key = `conformance:${crypto.randomUUID()}`\n\n const first = await store.increment(key, window, now)\n if (first.count !== 1) throw new ConformanceError('rate limit store', `expected a new key to start at 1, received ${first.count}`)\n if (first.resetAt !== now + window) {\n throw new ConformanceError('rate limit store', `expected the window to end at ${now + window}, received ${first.resetAt}`)\n }\n\n const second = await store.increment(key, window, now + 1)\n if (second.count !== 2) throw new ConformanceError('rate limit store', `expected the second request to count 2, received ${second.count}`)\n if (second.resetAt !== first.resetAt) {\n throw new ConformanceError('rate limit store', 'a request inside the window must not extend it')\n }\n\n const other = await store.increment(`conformance:${crypto.randomUUID()}`, window, now)\n if (other.count !== 1) throw new ConformanceError('rate limit store', 'one key consumed another key budget')\n\n const expired = await store.increment(key, window, first.resetAt)\n if (expired.count !== 1) throw new ConformanceError('rate limit store', 'an elapsed window must start a new count')\n if (expired.resetAt !== first.resetAt + window) {\n throw new ConformanceError('rate limit store', 'an elapsed window must start a new window')\n }\n}\n\nexport type AuthSecretProvider = (environment: NodeJS.ProcessEnv) => string | Promise<string>\n\n// A secret that changes between restarts signs out every session, and a short one is guessable. Neither shows up\n// until it is already in production, so the contract is checked against the provider an application wired.\nexport async function assertAuthSecretConformance(secret: AuthSecretProvider, options: { environmentKey?: string } = {}) {\n const key = options.environmentKey ?? 'AUTH_SECRET'\n const configured = 'configured-secret-value-that-is-long-enough'\n\n const first = await secret({})\n if (typeof first !== 'string' || !first.trim()) throw new ConformanceError('auth secret', 'provider returned no secret')\n if (first.length < 32) throw new ConformanceError('auth secret', `expected at least 32 characters, received ${first.length}`)\n if (new Set(first).size < 8) throw new ConformanceError('auth secret', 'secret does not look randomly generated')\n\n if ((await secret({})) !== first) {\n throw new ConformanceError('auth secret', 'secret changed between calls, which signs out every session on restart')\n }\n if ((await secret({ [key]: configured })) !== configured) {\n throw new ConformanceError('auth secret', `${key} must take precedence over a generated secret`)\n }\n}\n\nexport type RealtimePublisherProbe = { publish: (channel: string, data: unknown) => boolean; close: () => Promise<void> }\n\n// A publisher that accepts every channel turns a burst into unbounded memory, and one that accepts work after close\n// loses publications during shutdown. Both appear only under load.\nexport async function assertRealtimePublisherConformance(create: () => RealtimePublisherProbe, options: { probes?: number } = {}) {\n const probes = options.probes ?? 5_000\n const bounded = create()\n let admitted = 0\n for (let attempt = 0; attempt < probes; attempt++) if (bounded.publish(`conformance-${attempt}`, { attempt })) admitted += 1\n if (admitted === probes) throw new ConformanceError('realtime publisher', `accepted all ${probes} channels without a capacity limit`)\n if (admitted === 0) throw new ConformanceError('realtime publisher', 'rejected every publication')\n await bounded.close()\n\n const closed = create()\n await closed.close()\n if (closed.publish('conformance', {})) throw new ConformanceError('realtime publisher', 'accepted work after it was closed')\n}\n\nexport type SmtpConfigReader = (environment: NodeJS.ProcessEnv) => { host: string; port: number; from: string } | undefined\n\n// Half-configured SMTP is the failure that reaches production, because nothing sends mail until something needs to.\nexport function assertSmtpConfigConformance(read: SmtpConfigReader) {\n if (read({}) !== undefined) throw new ConformanceError('SMTP configuration', 'expected no configuration when nothing is set')\n\n const configured = read({ SMTP_HOST: 'smtp.example', EMAIL_FROM: 'app@example.com' })\n if (!configured) throw new ConformanceError('SMTP configuration', 'expected a configuration from a host and sender')\n if (configured.port !== 587)\n throw new ConformanceError('SMTP configuration', `expected the default port 587, received ${configured.port}`)\n\n rejects(read, { SMTP_HOST: 'smtp.example' }, 'a host without a sender')\n rejects(read, { EMAIL_FROM: 'app@example.com' }, 'a sender without a host')\n rejects(read, { SMTP_HOST: 'smtp.example', EMAIL_FROM: 'app@example.com', SMTP_PORT: '70000' }, 'a port outside the valid range')\n rejects(read, { SMTP_HOST: 'smtp.example', EMAIL_FROM: 'app@example.com', SMTP_USER: 'user' }, 'a user without a password')\n}\n\nfunction rejects(read: SmtpConfigReader, environment: NodeJS.ProcessEnv, scenario: string) {\n try {\n read(environment)\n } catch {\n return\n }\n throw new ConformanceError('SMTP configuration', `expected ${scenario} to be rejected`)\n}\n\nexport type DatabaseTarget = { provider: 'sqlite'; file: string } | { provider: 'postgres'; url: string }\n\nexport type DatabaseTargetResolver = (options: { databaseUrl?: string; sqliteFile: string }) => DatabaseTarget\n\nexport function assertDatabaseTargetConformance(resolve: DatabaseTargetResolver) {\n const sqliteFile = '/data/application.sqlite'\n const sqlite = resolve({ sqliteFile })\n if (sqlite.provider !== 'sqlite' || sqlite.file !== sqliteFile) {\n throw new ConformanceError('default database target', 'expected the configured SQLite file')\n }\n\n for (const url of ['postgres://user:secret@database/application', 'postgresql://user:secret@database/application']) {\n const target = resolve({ databaseUrl: url, sqliteFile })\n if (target.provider !== 'postgres' || target.url !== url) {\n throw new ConformanceError('PostgreSQL database target', `expected the configured ${new URL(url).protocol} URL`)\n }\n }\n\n try {\n resolve({ databaseUrl: 'https://database.example/application', sqliteFile })\n } catch {\n return\n }\n throw new ConformanceError('invalid database target', 'expected a non-PostgreSQL URL to be rejected')\n}\n\nexport function assertPostHogBrowserConformance(options: Record<string, unknown>) {\n if (typeof options.api_host !== 'string' || !options.api_host.trim()) {\n throw new ConformanceError('PostHog browser initialization', 'api_host must be configured')\n }\n if (typeof options.ui_host !== 'string' || !options.ui_host.trim()) {\n throw new ConformanceError('PostHog browser initialization', 'ui_host must be configured')\n }\n if (typeof options.defaults !== 'string' || !options.defaults.trim()) {\n throw new ConformanceError('PostHog browser initialization', 'SDK defaults must be pinned')\n }\n if (!options.capture_exceptions) {\n throw new ConformanceError('PostHog browser initialization', 'exception autocapture must be enabled')\n }\n if (options.capture_pageview !== 'history_change') {\n throw new ConformanceError('PostHog browser initialization', 'SPA pageviews must follow history changes')\n }\n if (options.capture_performance !== true) {\n throw new ConformanceError('PostHog browser initialization', 'browser performance capture must be enabled')\n }\n if (options.person_profiles !== 'identified_only') {\n throw new ConformanceError('PostHog browser initialization', 'person profiles must be limited to identified users')\n }\n if (options.mask_personal_data_properties !== true) {\n throw new ConformanceError('PostHog browser initialization', 'personal-data URL properties must be masked')\n }\n if (!Array.isArray(options.custom_personal_data_properties) || !options.custom_personal_data_properties.includes('token')) {\n throw new ConformanceError('PostHog browser initialization', 'token query parameters must be masked')\n }\n const recording = options.session_recording\n if (!recording || typeof recording !== 'object' || !('maskAllInputs' in recording) || recording.maskAllInputs !== true) {\n throw new ConformanceError('PostHog browser initialization', 'session replay must mask all inputs by default')\n }\n const logs = serviceName(options.logs)\n const metrics = serviceName(options.metrics)\n if ((logs || metrics) && (!logs || logs !== metrics)) {\n throw new ConformanceError('PostHog browser initialization', 'logs and metrics must share one service name')\n }\n}\n\nfunction serviceName(value: unknown) {\n if (!value || typeof value !== 'object' || !('serviceName' in value) || typeof value.serviceName !== 'string') return undefined\n return value.serviceName.trim() || undefined\n}\n\ntype PostHogContextParser = (\n request: Request,\n options?: { authenticatedDistinctId?: string; allowAnonymousDistinctId?: boolean },\n) => { distinctId?: string; sessionId?: string; properties: { $session_id?: string } }\n\nexport function assertPostHogRequestConformance(parse: PostHogContextParser) {\n const matched = parse(postHogRequest('person-123', 'session-456'), { authenticatedDistinctId: 'person-123' })\n if (matched.distinctId !== 'person-123' || matched.sessionId !== 'session-456' || matched.properties.$session_id !== 'session-456') {\n throw new ConformanceError('authenticated PostHog request', 'expected verified identity and session propagation')\n }\n const spoofed = parse(postHogRequest('attacker', 'session-456'), { authenticatedDistinctId: 'person-123' })\n if (spoofed.distinctId !== undefined) {\n throw new ConformanceError('spoofed PostHog request', 'unverified distinct id was trusted')\n }\n const malformed = parse(postHogRequest('person-123', 'x'.repeat(129)), { authenticatedDistinctId: 'person-123' })\n if (malformed.sessionId !== undefined || malformed.properties.$session_id !== undefined) {\n throw new ConformanceError('malformed PostHog request', 'unbounded session id was propagated')\n }\n}\n\nfunction postHogRequest(distinctId: string, sessionId: string) {\n return new Request('https://app.example/action', {\n headers: { 'x-posthog-distinct-id': distinctId, 'x-posthog-session-id': sessionId },\n })\n}\n\nasync function accepted(scenario: string, work: () => void | Promise<void>) {\n try {\n await work()\n } catch (error) {\n throw new ConformanceError(scenario, 'expected request to be accepted', { cause: error })\n }\n}\n\nasync function rejected(scenario: string, work: () => void | Promise<void>) {\n try {\n await work()\n } catch {\n return\n }\n throw new ConformanceError(scenario, 'expected request to be rejected')\n}\n\nasync function responseBody(response: Response, scenario: string): Promise<Record<string, unknown>> {\n try {\n const body: unknown = await response.json()\n if (body && typeof body === 'object') return body as Record<string, unknown>\n } catch (error) {\n throw new ConformanceError(scenario, 'response body must be JSON', { cause: error })\n }\n throw new ConformanceError(scenario, 'response body must be an object')\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/conformance/index.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAiB,SAAQ,KAAK;IAEvB,QAAQ;IADnB,YACW,QAAgB,EACzB,OAAe,E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;IACR,CAAC;IACD,MAAM,IAAI,gBAAgB,CAAC,QAAQ,EAAE,iCAAiC,CAAC,CAAA;AACzE,CAAC","sourcesContent":["class ConformanceError extends Error {\n constructor(\n readonly scenario: string,\n message: string,\n options: { cause?: unknown } = {},\n ) {\n super(`${scenario}: ${message}`, options.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'ConformanceError'\n }\n}\n\nexport async function assertMutationOriginConformance(\n guard: (request: Request) => void | Promise<void>,\n options: { trustForwardedHeaders?: boolean } = {},\n) {\n await accepted('same-origin request', () =>\n guard(\n new Request('https://app.example/action', {\n method: 'POST',\n headers: { origin: 'https://app.example', 'sec-fetch-site': 'same-origin' },\n }),\n ),\n )\n await rejected('cross-origin request', () =>\n guard(\n new Request('https://app.example/action', {\n method: 'POST',\n headers: { origin: 'https://attacker.example', 'sec-fetch-site': 'cross-site' },\n }),\n ),\n )\n await rejected('missing-origin request', () => guard(new Request('https://app.example/action', { method: 'POST' })))\n if (!options.trustForwardedHeaders) {\n await rejected('spoofed forwarded-origin request', () =>\n guard(\n new Request('https://app.example/action', {\n method: 'POST',\n headers: {\n origin: 'https://attacker.example',\n 'x-forwarded-host': 'attacker.example',\n 'x-forwarded-proto': 'https',\n },\n }),\n ),\n )\n }\n}\n\nexport type SqlitePragmaReader = (name: 'journal_mode' | 'synchronous' | 'busy_timeout' | 'foreign_keys') => unknown\n\nexport async function assertSqliteConformance(readPragma: SqlitePragmaReader) {\n const values = {\n journalMode: String(await readPragma('journal_mode')).toLowerCase(),\n synchronous: Number(await readPragma('synchronous')),\n busyTimeout: Number(await readPragma('busy_timeout')),\n foreignKeys: Number(await readPragma('foreign_keys')),\n }\n if (values.journalMode !== 'wal' && values.journalMode !== 'memory') {\n throw new ConformanceError('SQLite journal mode', `expected wal or memory, received ${values.journalMode}`)\n }\n if (values.synchronous !== 2) {\n throw new ConformanceError('SQLite synchronous mode', `expected FULL (2), received ${values.synchronous}`)\n }\n if (values.busyTimeout !== 5000) {\n throw new ConformanceError('SQLite busy timeout', `expected 5000, received ${values.busyTimeout}`)\n }\n if (values.foreignKeys !== 1) {\n throw new ConformanceError('SQLite foreign keys', `expected enabled (1), received ${values.foreignKeys}`)\n }\n}\n\nexport type DatabaseTarget = { provider: 'sqlite'; file: string } | { provider: 'postgres'; url: string }\n\nexport type DatabaseTargetResolver = (options: { databaseUrl?: string; sqliteFile: string }) => DatabaseTarget\n\nexport function assertDatabaseTargetConformance(resolve: DatabaseTargetResolver) {\n const sqliteFile = '/data/application.sqlite'\n const sqlite = resolve({ sqliteFile })\n if (sqlite.provider !== 'sqlite' || sqlite.file !== sqliteFile) {\n throw new ConformanceError('default database target', 'expected the configured SQLite file')\n }\n\n for (const url of ['postgres://user:secret@database/application', 'postgresql://user:secret@database/application']) {\n const target = resolve({ databaseUrl: url, sqliteFile })\n if (target.provider !== 'postgres' || target.url !== url) {\n throw new ConformanceError('PostgreSQL database target', `expected the configured ${new URL(url).protocol} URL`)\n }\n }\n\n try {\n resolve({ databaseUrl: 'https://database.example/application', sqliteFile })\n } catch {\n return\n }\n throw new ConformanceError('invalid database target', 'expected a non-PostgreSQL URL to be rejected')\n}\n\nasync function accepted(scenario: string, work: () => void | Promise<void>) {\n try {\n await work()\n } catch (error) {\n throw new ConformanceError(scenario, 'expected request to be accepted', { cause: error })\n }\n}\n\nasync function rejected(scenario: string, work: () => void | Promise<void>) {\n try {\n await work()\n } catch {\n return\n }\n throw new ConformanceError(scenario, 'expected request to be rejected')\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { type PostgresJsDatabase } from 'drizzle-orm/postgres-js';
2
2
  import postgres, { type Sql } from 'postgres';
3
- import { type RateLimitStore } from '../server/rate-limit.js';
4
3
  export type PostgresClientOptions = NonNullable<Parameters<typeof postgres>[1]>;
5
4
  export type OpenDrizzlePostgresOptions<TSchema extends Record<string, unknown>> = {
6
5
  url: string;
@@ -12,7 +11,3 @@ export type DrizzlePostgresConnection<TSchema extends Record<string, unknown>> =
12
11
  client: Sql;
13
12
  };
14
13
  export declare function openDrizzlePostgres<TSchema extends Record<string, unknown>>(options: OpenDrizzlePostgresOptions<TSchema>): DrizzlePostgresConnection<TSchema>;
15
- export declare function migrateDrizzlePostgres<TSchema extends Record<string, unknown>>(connection: DrizzlePostgresConnection<TSchema>, migrationsFolder: string): Promise<void>;
16
- export declare function closeDrizzlePostgres(connection: Pick<DrizzlePostgresConnection<Record<string, unknown>>, 'client'>, timeout?: number): Promise<void>;
17
- export declare function postgresRateLimitStore(client: Sql, table?: string): RateLimitStore;
18
- export declare function redactedPostgresUrl(source: string): string;
@@ -1,7 +1,5 @@
1
1
  import { drizzle } from 'drizzle-orm/postgres-js';
2
- import { migrate } from 'drizzle-orm/postgres-js/migrator';
3
2
  import postgres, {} from 'postgres';
4
- import { rateLimitTable } from '../server/rate-limit.js';
5
3
  export function openDrizzlePostgres(options) {
6
4
  const client = postgres(options.url, {
7
5
  max: 10,
@@ -15,36 +13,4 @@ export function openDrizzlePostgres(options) {
15
13
  const database = drizzle(client, { schema: options.schema });
16
14
  return { database, client };
17
15
  }
18
- export async function migrateDrizzlePostgres(connection, migrationsFolder) {
19
- await migrate(connection.database, { migrationsFolder });
20
- }
21
- export async function closeDrizzlePostgres(connection, timeout = 5) {
22
- await connection.client.end({ timeout });
23
- }
24
- // One statement so concurrent replicas cannot both read a stale count and write the same increment.
25
- export function postgresRateLimitStore(client, table = 'rate_limit') {
26
- const name = client(rateLimitTable(table));
27
- return {
28
- async increment(key, windowSeconds, now) {
29
- const resetAt = now + windowSeconds;
30
- const [row] = await client `
31
- insert into ${name} (key, count, reset_at) values (${key}, 1, ${resetAt})
32
- on conflict (key) do update set
33
- count = case when ${name}.reset_at <= ${now} then 1 else ${name}.count + 1 end,
34
- reset_at = case when ${name}.reset_at <= ${now} then ${resetAt} else ${name}.reset_at end
35
- returning count, reset_at
36
- `;
37
- if (!row)
38
- throw new Error('rate limit increment returned no row');
39
- // A bigint column arrives as a string unless the client configures a parser, and the store owns its own type.
40
- return { count: Number(row.count), resetAt: Number(row.reset_at) };
41
- },
42
- };
43
- }
44
- export function redactedPostgresUrl(source) {
45
- const url = new URL(source);
46
- url.username = '';
47
- url.password = '';
48
- return url.toString();
49
- }
50
16
  //# sourceMappingURL=postgres.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../../src/database/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAA2B,MAAM,yBAAyB,CAAA;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAA;AAC1D,OAAO,QAAQ,EAAE,EAAY,MAAM,UAAU,CAAA;AAC7C,OAAO,EAAE,cAAc,EAAuB,MAAM,yBAAyB,CAAA;AAe7E,MAAM,UAAU,mBAAmB,CACjC,OAA4C;IAE5C,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE;QACnC,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,GAAG,EAAE,CAAC,SAAS;QACzB,KAAK,EAAE;YACL,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE;YAC1F,OAAO,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE;SAChG;QACD,GAAG,OAAO,CAAC,MAAM;KAClB,CAAC,CAAA;IACF,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;IAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAA;AAC7B,CAAC;AAED,MAAM,CA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;IACjB,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAA;AACvB,CAAC","sourcesContent":["import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport { migrate } from 'drizzle-orm/postgres-js/migrator'\nimport postgres, { type Sql } from 'postgres'\nimport { rateLimitTable, type RateLimitStore } from '../server/rate-limit.js'\n\nexport type PostgresClientOptions = NonNullable<Parameters<typeof postgres>[1]>\n\nexport type OpenDrizzlePostgresOptions<TSchema extends Record<string, unknown>> = {\n url: string\n schema: TSchema\n client?: PostgresClientOptions\n}\n\nexport type DrizzlePostgresConnection<TSchema extends Record<string, unknown>> = {\n database: PostgresJsDatabase<TSchema>\n client: Sql\n}\n\nexport function openDrizzlePostgres<TSchema extends Record<string, unknown>>(\n options: OpenDrizzlePostgresOptions<TSchema>,\n): DrizzlePostgresConnection<TSchema> {\n const client = postgres(options.url, {\n max: 10,\n onnotice: () => undefined,\n types: {\n bigint: { to: 20, from: [20], serialize: (value: number) => String(value), parse: Number },\n numeric: { to: 1700, from: [1700], serialize: (value: number) => String(value), parse: Number },\n },\n ...options.client,\n })\n const database = drizzle(client, { schema: options.schema })\n return { database, client }\n}\n\nexport async function migrateDrizzlePostgres<TSchema extends Record<string, unknown>>(\n connection: DrizzlePostgresConnection<TSchema>,\n migrationsFolder: string,\n) {\n await migrate(connection.database, { migrationsFolder })\n}\n\nexport async function closeDrizzlePostgres(connection: Pick<DrizzlePostgresConnection<Record<string, unknown>>, 'client'>, timeout = 5) {\n await connection.client.end({ timeout })\n}\n\n// One statement so concurrent replicas cannot both read a stale count and write the same increment.\nexport function postgresRateLimitStore(client: Sql, table = 'rate_limit'): RateLimitStore {\n const name = client(rateLimitTable(table))\n return {\n async increment(key, windowSeconds, now) {\n const resetAt = now + windowSeconds\n const [row] = await client<{ count: number | string; reset_at: number | string }[]>`\n insert into ${name} (key, count, reset_at) values (${key}, 1, ${resetAt})\n on conflict (key) do update set\n count = case when ${name}.reset_at <= ${now} then 1 else ${name}.count + 1 end,\n reset_at = case when ${name}.reset_at <= ${now} then ${resetAt} else ${name}.reset_at end\n returning count, reset_at\n `\n if (!row) throw new Error('rate limit increment returned no row')\n // A bigint column arrives as a string unless the client configures a parser, and the store owns its own type.\n return { count: Number(row.count), resetAt: Number(row.reset_at) }\n },\n }\n}\n\nexport function redactedPostgresUrl(source: string) {\n const url = new URL(source)\n url.username = ''\n url.password = ''\n return url.toString()\n}\n"]}
1
+ {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../../src/database/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAA2B,MAAM,yBAAyB,CAAA;AAC1E,OAAO,QAAQ,EAAE,EAAY,MAAM,UAAU,CAAA;AAe7C,MAAM,UAAU,mBAAmB,CACjC,OAA4C;IAE5C,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE;QACnC,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,GAAG,EAAE,CAAC,SAAS;QACzB,KAAK,EAAE;YACL,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE;YAC1F,OAAO,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE;SAChG;QACD,GAAG,OAAO,CAAC,MAAM;KAClB,CAAC,CAAA;IACF,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;IAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAA;AAC7B,CAAC","sourcesContent":["import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport postgres, { type Sql } from 'postgres'\n\nexport type PostgresClientOptions = NonNullable<Parameters<typeof postgres>[1]>\n\nexport type OpenDrizzlePostgresOptions<TSchema extends Record<string, unknown>> = {\n url: string\n schema: TSchema\n client?: PostgresClientOptions\n}\n\nexport type DrizzlePostgresConnection<TSchema extends Record<string, unknown>> = {\n database: PostgresJsDatabase<TSchema>\n client: Sql\n}\n\nexport function openDrizzlePostgres<TSchema extends Record<string, unknown>>(\n options: OpenDrizzlePostgresOptions<TSchema>,\n): DrizzlePostgresConnection<TSchema> {\n const client = postgres(options.url, {\n max: 10,\n onnotice: () => undefined,\n types: {\n bigint: { to: 20, from: [20], serialize: (value: number) => String(value), parse: Number },\n numeric: { to: 1700, from: [1700], serialize: (value: number) => String(value), parse: Number },\n },\n ...options.client,\n })\n const database = drizzle(client, { schema: options.schema })\n return { database, client }\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import Database from 'better-sqlite3';
2
2
  import { type BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
3
- import { type RateLimitStore } from '../server/rate-limit.js';
4
3
  import { type SqlitePragmas } from './pragmas.js';
5
4
  export type { SqlitePragmas } from './pragmas.js';
6
5
  export type OpenSqliteOptions = {
@@ -8,7 +7,6 @@ export type OpenSqliteOptions = {
8
7
  pragmas?: SqlitePragmas | false;
9
8
  };
10
9
  export declare function openSqliteClient(file: string, options?: OpenSqliteOptions): Database.Database;
11
- export declare function configureSqlite(client: Database.Database, pragmas?: SqlitePragmas): Database.Database;
12
10
  export type OpenDrizzleSqliteOptions<TSchema extends Record<string, unknown>> = OpenSqliteOptions & {
13
11
  file: string;
14
12
  schema: TSchema;
@@ -20,4 +18,3 @@ export declare function openDrizzleSqlite<TSchema extends Record<string, unknown
20
18
  export declare function closeDrizzleSqlite(database: {
21
19
  $client: Database.Database;
22
20
  }): void;
23
- export declare function sqliteRateLimitStore(client: Database.Database, table?: string): RateLimitStore;