@wtfalch/keys 0.2.1 → 0.4.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.
@@ -6,6 +6,8 @@ import { keyPrefixOf, mintSecret, rotateSecret, secretMatches } from './secret.j
6
6
  import { keysIssuedCredentials } from './tables.js';
7
7
  import { verifyIssuedRowSignature } from './verify.js';
8
8
  export { ID_PATTERN, SIGNED_PREFIX, } from '../worker-contract.js';
9
+ export { createPostgresRateLimiter, } from './ratelimit.js';
10
+ export { createSigningGenerationMigrator, MAX_RESIGN_BATCH_SIZE, } from './resign.js';
9
11
  function rowsOf(result) {
10
12
  if (Array.isArray(result))
11
13
  return result;
@@ -27,7 +29,7 @@ function toSignableRow(row) {
27
29
  };
28
30
  }
29
31
  export function createCredentialIssuer(options) {
30
- const { db, worker, credential, verifyKeys, audit, prefix } = options;
32
+ const { db, worker, credential, verifyKeys, audit, prefix, rateLimiter } = options;
31
33
  const now = options.now ?? (() => Date.now());
32
34
  const table = keysIssuedCredentials;
33
35
  async function loadById(id, handle = db) {
@@ -78,6 +80,7 @@ export function createCredentialIssuer(options) {
78
80
  if (request.expiresAt <= now()) {
79
81
  return { ok: false, reason: 'expires_at_past' };
80
82
  }
83
+ const environment = request.environment ?? 'live';
81
84
  let minterAttestation = null;
82
85
  if (request.minter !== null) {
83
86
  const minterRow = await loadById(request.minter);
@@ -90,6 +93,11 @@ export function createCredentialIssuer(options) {
90
93
  return { ok: false, reason: 'minter_revoked' };
91
94
  if (minterRow.expiresAt <= now())
92
95
  return { ok: false, reason: 'minter_expired' };
96
+ // #47: a test key can only mint a test key, a live key only a live
97
+ // one -- the pairing the issue asked for, not just a label.
98
+ if (minterRow.environment !== environment) {
99
+ return { ok: false, reason: 'environment_mismatch' };
100
+ }
93
101
  minterAttestation = {
94
102
  row: toSignableRow(minterRow),
95
103
  signature: fromBase64Url(minterRow.signature),
@@ -127,6 +135,8 @@ export function createCredentialIssuer(options) {
127
135
  return 'minter_revoked';
128
136
  if (parent.expiresAt <= now())
129
137
  return 'minter_expired';
138
+ if (parent.environment !== environment)
139
+ return 'environment_mismatch';
130
140
  if (!minterAttestation ||
131
141
  parent.signature !== toBase64Url(minterAttestation.signature) ||
132
142
  canonicalJson(toSignableRow(parent)) !== canonicalJson(minterAttestation.row)) {
@@ -143,6 +153,7 @@ export function createCredentialIssuer(options) {
143
153
  signature: toBase64Url(result.signature),
144
154
  signingGenerationId: result.generationId,
145
155
  idempotencyKey: request.idempotencyKey ?? null,
156
+ environment,
146
157
  });
147
158
  return null;
148
159
  });
@@ -173,6 +184,24 @@ export function createCredentialIssuer(options) {
173
184
  const row = await loadByPrefix(keyPrefix);
174
185
  if (!row)
175
186
  return { ok: false, reason: 'not_found' };
187
+ // #45: spent on every attempt against a known credential, matched
188
+ // secret or not -- an unlimited number of wrong guesses against an
189
+ // identified row would otherwise let an attacker brute-force it past
190
+ // any per-successful-use limit. Before the signature check below, so a
191
+ // flood of requests against one credential id never reaches the more
192
+ // expensive Ed25519 verify.
193
+ // A `rateLimiter.check` failure is NOT caught, unlike #46's usage
194
+ // write below: rate limiting is a security control the host opted
195
+ // into, and failing open on it (silently never limiting anything
196
+ // whenever its store is unreachable) is a worse failure mode than a
197
+ // loud one a host notices in its own staging environment the first
198
+ // time the migration is missing or the store is down.
199
+ if (rateLimiter) {
200
+ const limit = await rateLimiter.check(row.id, now());
201
+ if (limit.limited) {
202
+ return { ok: false, reason: 'rate_limited', retryAfterMs: limit.retryAfterMs };
203
+ }
204
+ }
176
205
  // Verified before anything else is trusted about the row: a signature
177
206
  // check over the row's CURRENT fields refuses a row a raw UPDATE
178
207
  // tampered with, whatever that tamper changed.
@@ -184,26 +213,34 @@ export function createCredentialIssuer(options) {
184
213
  return { ok: false, reason: 'revoked' };
185
214
  if (now() >= row.expiresAt)
186
215
  return { ok: false, reason: 'expired' };
187
- if (secretMatches(secret, row.secretHash)) {
188
- return {
189
- ok: true,
190
- id: row.id,
191
- issuedById: row.issuedById,
192
- grants: row.grants,
193
- };
216
+ const matched = secretMatches(secret, row.secretHash) ||
217
+ (row.previousSecretHash !== null &&
218
+ row.previousValidUntil !== null &&
219
+ now() < row.previousValidUntil &&
220
+ secretMatches(secret, row.previousSecretHash));
221
+ if (!matched)
222
+ return { ok: false, reason: 'secret_mismatch' };
223
+ // #46: last-used/use-count, for an admin UI to read directly off the
224
+ // row -- best-effort. A write failure here is observability lost, not
225
+ // an authorization decision, so it must never turn an otherwise-genuine
226
+ // secret into a refusal; check() stays available for the one thing it
227
+ // exists to do even if this bookkeeping write cannot land.
228
+ try {
229
+ await db
230
+ .update(table)
231
+ .set({ lastUsedAt: new Date(now()), useCount: sql `${table.useCount} + 1` })
232
+ .where(eq(table.id, row.id));
194
233
  }
195
- if (row.previousSecretHash !== null &&
196
- row.previousValidUntil !== null &&
197
- now() < row.previousValidUntil &&
198
- secretMatches(secret, row.previousSecretHash)) {
199
- return {
200
- ok: true,
201
- id: row.id,
202
- issuedById: row.issuedById,
203
- grants: row.grants,
204
- };
234
+ catch {
235
+ // Swallowed by design -- see comment above.
205
236
  }
206
- return { ok: false, reason: 'secret_mismatch' };
237
+ return {
238
+ ok: true,
239
+ id: row.id,
240
+ issuedById: row.issuedById,
241
+ grants: row.grants,
242
+ environment: row.environment,
243
+ };
207
244
  }
208
245
  async function rotate(id, opts) {
209
246
  const row = await loadById(id);
@@ -324,6 +361,7 @@ export function createCredentialIssuer(options) {
324
361
  grants: row.grants,
325
362
  expiresAt: row.expiresAt,
326
363
  revokedAt: row.revokedAt ? row.revokedAt.getTime() : null,
364
+ environment: row.environment,
327
365
  });
328
366
  currentId = row.issuedById;
329
367
  }
@@ -0,0 +1,34 @@
1
+ import type { Db } from './index.js';
2
+ /**
3
+ * #45: a per-issued-credential abuse limit. `packages/worker/src/ratelimit.ts`
4
+ * already limits per `hostId` + the HOST's own service credential; nothing
5
+ * limited an END USER's individual issued key until this. `check()` consults
6
+ * `CreateCredentialIssuerOptions.rateLimiter`, when one is given, keyed by
7
+ * the credential's own `id` -- once the row is found (so a known
8
+ * credential's budget is spent on every attempt, matched secret or not,
9
+ * not only on a successful one), before its secret is verified.
10
+ */
11
+ export interface RateLimitResult {
12
+ readonly limited: boolean;
13
+ /** Milliseconds until the current window resets. Meaningful whether or not `limited`. */
14
+ readonly retryAfterMs: number;
15
+ }
16
+ export interface RateLimiter {
17
+ /** `now`: Unix milliseconds, the same clock `check()`'s own `now` option gives -- never read internally, so a fake clock in a test reaches this too. */
18
+ check(credentialId: string, now: number): Promise<RateLimitResult>;
19
+ }
20
+ export interface CreatePostgresRateLimiterOptions {
21
+ readonly db: Db;
22
+ /** Requests a single credential may make per window before `limited` is true. */
23
+ readonly limitPerWindow: number;
24
+ /** Milliseconds. Default 60_000. */
25
+ readonly windowMs?: number;
26
+ }
27
+ /**
28
+ * A fixed-window counter in the host's own Postgres, one bounded row per
29
+ * credential (`keys_issued_rate_limit_windows`, `0007_keys_rate_limit.sql`),
30
+ * atomically reset each window by a single upsert -- the same shape
31
+ * `packages/worker/src/ratelimit.ts`'s D1 `host_rate_limit_windows` uses, a
32
+ * level down: keyed by the end user's credential id, not the host's.
33
+ */
34
+ export declare function createPostgresRateLimiter(options: CreatePostgresRateLimiterOptions): RateLimiter;
@@ -0,0 +1,49 @@
1
+ import { sql } from 'drizzle-orm';
2
+ function rowsOf(result) {
3
+ if (Array.isArray(result))
4
+ return result;
5
+ return (result.rows ?? []);
6
+ }
7
+ /**
8
+ * A fixed-window counter in the host's own Postgres, one bounded row per
9
+ * credential (`keys_issued_rate_limit_windows`, `0007_keys_rate_limit.sql`),
10
+ * atomically reset each window by a single upsert -- the same shape
11
+ * `packages/worker/src/ratelimit.ts`'s D1 `host_rate_limit_windows` uses, a
12
+ * level down: keyed by the end user's credential id, not the host's.
13
+ */
14
+ export function createPostgresRateLimiter(options) {
15
+ const { db, limitPerWindow } = options;
16
+ const windowMs = options.windowMs ?? 60_000;
17
+ return {
18
+ async check(credentialId, now) {
19
+ const windowStart = Math.floor(now / windowMs) * windowMs;
20
+ const result = await db.execute(sql `
21
+ insert into keys_issued_rate_limit_windows (credential_id, window_start, count)
22
+ values (${credentialId}, ${windowStart}, 1)
23
+ on conflict (credential_id) do update set
24
+ window_start = excluded.window_start,
25
+ count = case
26
+ when keys_issued_rate_limit_windows.window_start = excluded.window_start
27
+ then keys_issued_rate_limit_windows.count + 1
28
+ else 1
29
+ end
30
+ returning window_start, count
31
+ `);
32
+ const [row] = rowsOf(result);
33
+ if (!row)
34
+ throw new Error('rate limit write returned no row');
35
+ // `count` is `integer` (int4), always JS-number-safe -- but a raw
36
+ // (non-query-builder) result is still driver-dependent about handing
37
+ // it back as a number or a numeric string, so `Number(...)` either
38
+ // way. `window_start` itself is never re-read from the row: the
39
+ // upsert always sets it to `excluded.window_start`, never
40
+ // conditionally kept, so it equals the `windowStart` just computed
41
+ // above.
42
+ const count = Number(row.count);
43
+ return {
44
+ limited: count > limitPerWindow,
45
+ retryAfterMs: windowStart + windowMs - now,
46
+ };
47
+ },
48
+ };
49
+ }
@@ -0,0 +1,55 @@
1
+ import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
2
+ import { type SerializedCredential, type WorkerClient, type WorkerErrorCode } from '../worker-contract.js';
3
+ type Db = PgDatabase<PgQueryResultHKT, any, any>;
4
+ /** The hard ceiling keeps one operator call within the Worker's documented request budget. */
5
+ export declare const MAX_RESIGN_BATCH_SIZE = 100;
6
+ export interface CreateSigningGenerationMigratorOptions<TGrant> {
7
+ readonly db: Db;
8
+ /** The Worker endpoint verifies the old signature and its host-scoped mint log before signing. */
9
+ readonly worker: Pick<WorkerClient<TGrant>, 'resign'>;
10
+ /** A valid, non-revoked operator caller credential carrying the `resign` grant. */
11
+ readonly credential: SerializedCredential;
12
+ }
13
+ /**
14
+ * A cursor is deliberately scoped to one source/target pair. Persist the
15
+ * whole value; accepting a bare row id would let an operator accidentally
16
+ * skip rows by reusing it for another migration.
17
+ */
18
+ export interface SigningGenerationCursor {
19
+ readonly fromGenerationId: string;
20
+ readonly toGenerationId: string;
21
+ readonly afterId: string;
22
+ }
23
+ export interface ResignGenerationBatchRequest {
24
+ readonly fromGenerationId: string;
25
+ readonly toGenerationId: string;
26
+ /** The exact public key for `toGenerationId`; every Worker result is verified locally before publish. */
27
+ readonly targetPublicKey: Uint8Array;
28
+ readonly cursor?: SigningGenerationCursor | null;
29
+ readonly limit: number;
30
+ }
31
+ export type ResignGenerationRefusalReason = WorkerErrorCode | 'conflict' | 'generation_mismatch' | 'target_signature_invalid';
32
+ interface ResignGenerationProgress {
33
+ /** Rows durably published during this call, in cursor order. */
34
+ readonly migratedIds: readonly string[];
35
+ /** Resume with this exact cursor. `null` means restart this source/target pass from the beginning. */
36
+ readonly resumeCursor: SigningGenerationCursor | null;
37
+ }
38
+ export type ResignGenerationBatchResult = (ResignGenerationProgress & {
39
+ readonly ok: true;
40
+ /** True means this cursor pass was exhausted, not that retirement is safe under concurrent writers. */
41
+ readonly complete: boolean;
42
+ }) | (ResignGenerationProgress & {
43
+ readonly ok: false;
44
+ readonly reason: ResignGenerationRefusalReason;
45
+ readonly failedId?: string;
46
+ /** Present when the Worker signed with a generation other than the requested target. */
47
+ readonly actualGenerationId?: string;
48
+ });
49
+ export interface SigningGenerationMigrator {
50
+ resignBatch(request: ResignGenerationBatchRequest): Promise<ResignGenerationBatchResult>;
51
+ /** An observation for rollout checks; it is not, by itself, proof that retirement is safe. */
52
+ countGenerationRows(generationId: string): Promise<number>;
53
+ }
54
+ export declare function createSigningGenerationMigrator<TGrant>(options: CreateSigningGenerationMigratorOptions<TGrant>): SigningGenerationMigrator;
55
+ export {};
@@ -0,0 +1,174 @@
1
+ import { and, asc, eq, gt, sql } from 'drizzle-orm';
2
+ import { ID_PATTERN, } from '../worker-contract.js';
3
+ import { fromBase64Url, toBase64Url } from './codec.js';
4
+ import { canonicalJson } from './encoding.js';
5
+ import { keysIssuedCredentials } from './tables.js';
6
+ import { verifyIssuedRowSignature } from './verify.js';
7
+ /** The hard ceiling keeps one operator call within the Worker's documented request budget. */
8
+ export const MAX_RESIGN_BATCH_SIZE = 100;
9
+ function toSignableRow(row) {
10
+ return {
11
+ id: row.id,
12
+ issuedById: row.issuedById,
13
+ keyPrefix: row.keyPrefix,
14
+ secretHash: row.secretHash,
15
+ previousSecretHash: row.previousSecretHash,
16
+ previousValidUntil: row.previousValidUntil,
17
+ grants: row.grants,
18
+ expiresAt: row.expiresAt,
19
+ };
20
+ }
21
+ function sameSignedState(a, b) {
22
+ return (a.signature === b.signature &&
23
+ canonicalJson(toSignableRow(a)) === canonicalJson(toSignableRow(b)));
24
+ }
25
+ function cursorAfter(fromGenerationId, toGenerationId, afterId) {
26
+ return afterId === null ? null : { fromGenerationId, toGenerationId, afterId };
27
+ }
28
+ function validRequest(request) {
29
+ if (!ID_PATTERN.test(request.fromGenerationId) || !ID_PATTERN.test(request.toGenerationId)) {
30
+ return false;
31
+ }
32
+ if (request.fromGenerationId === request.toGenerationId)
33
+ return false;
34
+ if (!Number.isSafeInteger(request.limit) ||
35
+ request.limit < 1 ||
36
+ request.limit > MAX_RESIGN_BATCH_SIZE) {
37
+ return false;
38
+ }
39
+ if (!(request.targetPublicKey instanceof Uint8Array) ||
40
+ request.targetPublicKey.byteLength !== 32) {
41
+ return false;
42
+ }
43
+ if (request.cursor) {
44
+ return (request.cursor.fromGenerationId === request.fromGenerationId &&
45
+ request.cursor.toGenerationId === request.toGenerationId &&
46
+ ID_PATTERN.test(request.cursor.afterId));
47
+ }
48
+ return true;
49
+ }
50
+ export function createSigningGenerationMigrator(options) {
51
+ const { db, worker, credential } = options;
52
+ const table = keysIssuedCredentials;
53
+ async function resignBatch(request) {
54
+ if (!validRequest(request)) {
55
+ return { ok: false, reason: 'bad_request', migratedIds: [], resumeCursor: null };
56
+ }
57
+ // Own the bytes for the duration of the batch so a caller cannot mutate
58
+ // the supplied view between per-row verification calls.
59
+ const targetPublicKey = new Uint8Array(request.targetPublicKey);
60
+ const afterId = request.cursor?.afterId;
61
+ const condition = afterId
62
+ ? and(eq(table.signingGenerationId, request.fromGenerationId), gt(table.id, afterId))
63
+ : eq(table.signingGenerationId, request.fromGenerationId);
64
+ const rows = await db
65
+ .select()
66
+ .from(table)
67
+ .where(condition)
68
+ .orderBy(asc(table.id))
69
+ .limit(request.limit + 1);
70
+ const candidates = rows.slice(0, request.limit);
71
+ const migratedIds = [];
72
+ let lastPublishedId = afterId ?? null;
73
+ for (const row of candidates) {
74
+ const signable = toSignableRow(row);
75
+ const result = await worker.resign({
76
+ requestId: crypto.randomUUID(),
77
+ credential,
78
+ row: signable,
79
+ oldSignature: fromBase64Url(row.signature),
80
+ oldGenerationId: request.fromGenerationId,
81
+ });
82
+ if (!result.ok) {
83
+ return {
84
+ ok: false,
85
+ reason: result.error.code,
86
+ failedId: row.id,
87
+ migratedIds,
88
+ resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
89
+ };
90
+ }
91
+ if (result.generationId !== request.toGenerationId) {
92
+ return {
93
+ ok: false,
94
+ reason: 'generation_mismatch',
95
+ failedId: row.id,
96
+ actualGenerationId: result.generationId,
97
+ migratedIds,
98
+ resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
99
+ };
100
+ }
101
+ const targetSignature = result.signature instanceof Uint8Array ? new Uint8Array(result.signature) : null;
102
+ let targetSignatureValid = false;
103
+ if (targetSignature) {
104
+ try {
105
+ targetSignatureValid = await verifyIssuedRowSignature(signable, targetSignature, [
106
+ targetPublicKey,
107
+ ]);
108
+ }
109
+ catch {
110
+ targetSignatureValid = false;
111
+ }
112
+ }
113
+ if (!targetSignature || !targetSignatureValid) {
114
+ return {
115
+ ok: false,
116
+ reason: 'target_signature_invalid',
117
+ failedId: row.id,
118
+ migratedIds,
119
+ resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
120
+ };
121
+ }
122
+ const published = await db.transaction(async (tx) => {
123
+ const [current] = await tx.select().from(table).where(eq(table.id, row.id)).for('update');
124
+ if (!current ||
125
+ current.signingGenerationId !== request.fromGenerationId ||
126
+ !sameSignedState(current, row)) {
127
+ return false;
128
+ }
129
+ await tx
130
+ .update(table)
131
+ .set({
132
+ signature: toBase64Url(targetSignature),
133
+ signingGenerationId: result.generationId,
134
+ })
135
+ .where(and(eq(table.id, row.id), eq(table.signingGenerationId, request.fromGenerationId), eq(table.signature, row.signature)));
136
+ return true;
137
+ });
138
+ if (!published) {
139
+ return {
140
+ ok: false,
141
+ reason: 'conflict',
142
+ failedId: row.id,
143
+ migratedIds,
144
+ resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
145
+ };
146
+ }
147
+ migratedIds.push(row.id);
148
+ lastPublishedId = row.id;
149
+ }
150
+ const complete = rows.length <= request.limit;
151
+ return {
152
+ ok: true,
153
+ complete,
154
+ migratedIds,
155
+ resumeCursor: complete
156
+ ? null
157
+ : cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
158
+ };
159
+ }
160
+ async function countGenerationRows(generationId) {
161
+ if (!ID_PATTERN.test(generationId))
162
+ throw new TypeError('generationId must match ID_PATTERN');
163
+ const result = await db.execute(sql `
164
+ select count(*)::integer as count
165
+ from public.keys_issued_credentials
166
+ where signing_generation_id = ${generationId}
167
+ `);
168
+ const rows = Array.isArray(result)
169
+ ? result
170
+ : (result.rows ?? []);
171
+ return Number(rows[0]?.count ?? 0);
172
+ }
173
+ return { resignBatch, countGenerationRows };
174
+ }
@@ -16,6 +16,16 @@
16
16
  * a lazily-declared drizzle table needs an `AnyPgColumn` callback and buys
17
17
  * nothing this package's own tests check, since the constraint that actually
18
18
  * runs is the one in the SQL migration.
19
+ *
20
+ * `environment` (#47) is not part of `SignableRow` -- unsigned metadata, same
21
+ * footing as `idempotencyKey`/`createdAt`. `0005_keys_environment.sql`'s
22
+ * extended `keys_issued_guard()` trigger is what keeps it trustworthy: set
23
+ * once at `issue()`, immutable for the row's life.
24
+ *
25
+ * `lastUsedAt`/`useCount` (#46, `0006_keys_usage.sql`) are the one pair on
26
+ * this row that is NOT set-once: `check()` writes both on every successful
27
+ * verification, so -- unlike `environment` -- `keys_issued_guard()` leaves
28
+ * them out of its immutable-columns check.
19
29
  */
20
30
  export declare const keysIssuedCredentials: import("drizzle-orm/pg-core").PgTableWithColumns<{
21
31
  name: "keys_issued_credentials";
@@ -208,6 +218,23 @@ export declare const keysIssuedCredentials: import("drizzle-orm/pg-core").PgTabl
208
218
  identity: undefined;
209
219
  generated: undefined;
210
220
  }, {}, {}>;
221
+ environment: import("drizzle-orm/pg-core").PgColumn<{
222
+ name: "environment";
223
+ tableName: "keys_issued_credentials";
224
+ dataType: "string";
225
+ columnType: "PgText";
226
+ data: string;
227
+ driverParam: string;
228
+ notNull: true;
229
+ hasDefault: false;
230
+ isPrimaryKey: false;
231
+ isAutoincrement: false;
232
+ hasRuntimeDefault: false;
233
+ enumValues: [string, ...string[]];
234
+ baseColumn: never;
235
+ identity: undefined;
236
+ generated: undefined;
237
+ }, {}, {}>;
211
238
  createdAt: import("drizzle-orm/pg-core").PgColumn<{
212
239
  name: "created_at";
213
240
  tableName: "keys_issued_credentials";
@@ -242,6 +269,40 @@ export declare const keysIssuedCredentials: import("drizzle-orm/pg-core").PgTabl
242
269
  identity: undefined;
243
270
  generated: undefined;
244
271
  }, {}, {}>;
272
+ lastUsedAt: import("drizzle-orm/pg-core").PgColumn<{
273
+ name: "last_used_at";
274
+ tableName: "keys_issued_credentials";
275
+ dataType: "date";
276
+ columnType: "PgTimestamp";
277
+ data: Date;
278
+ driverParam: string;
279
+ notNull: false;
280
+ hasDefault: false;
281
+ isPrimaryKey: false;
282
+ isAutoincrement: false;
283
+ hasRuntimeDefault: false;
284
+ enumValues: undefined;
285
+ baseColumn: never;
286
+ identity: undefined;
287
+ generated: undefined;
288
+ }, {}, {}>;
289
+ useCount: import("drizzle-orm/pg-core").PgColumn<{
290
+ name: "use_count";
291
+ tableName: "keys_issued_credentials";
292
+ dataType: "number";
293
+ columnType: "PgBigInt53";
294
+ data: number;
295
+ driverParam: string | number;
296
+ notNull: true;
297
+ hasDefault: true;
298
+ isPrimaryKey: false;
299
+ isAutoincrement: false;
300
+ hasRuntimeDefault: false;
301
+ enumValues: undefined;
302
+ baseColumn: never;
303
+ identity: undefined;
304
+ generated: undefined;
305
+ }, {}, {}>;
245
306
  };
246
307
  dialect: "pg";
247
308
  }>;
@@ -17,6 +17,16 @@ import { bigint, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
17
17
  * a lazily-declared drizzle table needs an `AnyPgColumn` callback and buys
18
18
  * nothing this package's own tests check, since the constraint that actually
19
19
  * runs is the one in the SQL migration.
20
+ *
21
+ * `environment` (#47) is not part of `SignableRow` -- unsigned metadata, same
22
+ * footing as `idempotencyKey`/`createdAt`. `0005_keys_environment.sql`'s
23
+ * extended `keys_issued_guard()` trigger is what keeps it trustworthy: set
24
+ * once at `issue()`, immutable for the row's life.
25
+ *
26
+ * `lastUsedAt`/`useCount` (#46, `0006_keys_usage.sql`) are the one pair on
27
+ * this row that is NOT set-once: `check()` writes both on every successful
28
+ * verification, so -- unlike `environment` -- `keys_issued_guard()` leaves
29
+ * them out of its immutable-columns check.
20
30
  */
21
31
  export const keysIssuedCredentials = pgTable('keys_issued_credentials', {
22
32
  id: text('id').primaryKey(),
@@ -30,6 +40,9 @@ export const keysIssuedCredentials = pgTable('keys_issued_credentials', {
30
40
  signature: text('signature').notNull(),
31
41
  signingGenerationId: text('signing_generation_id').notNull(),
32
42
  idempotencyKey: text('idempotency_key'),
43
+ environment: text('environment').notNull(),
33
44
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
34
45
  revokedAt: timestamp('revoked_at', { withTimezone: true }),
46
+ lastUsedAt: timestamp('last_used_at', { withTimezone: true }),
47
+ useCount: bigint('use_count', { mode: 'number' }).notNull().default(0),
35
48
  });
@@ -0,0 +1,52 @@
1
+ -- #47: a built-in `environment` on every issued credential, so a host's
2
+ -- sandbox/live split is a structured field rather than a convention the host
3
+ -- invents on top of `key_prefix`. Additive; do not edit copied migrations.
4
+ --
5
+ -- Not part of SignableRow (worker-contract.ts): the Worker's signature never
6
+ -- covers it, same footing as idempotency_key and created_at. What keeps it
7
+ -- trustworthy despite that is keys_issued_guard() below, extended to refuse
8
+ -- any UPDATE that changes it -- set once at issue(), for that row's life.
9
+ --
10
+ -- Backfilled 'live' on existing rows: every row minted before this migration
11
+ -- was minted under a single, unqualified prefix, which today's default
12
+ -- environment ('live') matches.
13
+ alter table keys_issued_credentials
14
+ add column if not exists environment text not null default 'live';
15
+ alter table keys_issued_credentials alter column environment drop default;
16
+
17
+ do $$
18
+ begin
19
+ if not exists (
20
+ select 1 from pg_constraint
21
+ where conname = 'keys_issued_credentials_environment_check'
22
+ ) then
23
+ alter table keys_issued_credentials
24
+ add constraint keys_issued_credentials_environment_check
25
+ check (environment in ('live', 'test'));
26
+ end if;
27
+ end
28
+ $$;
29
+
30
+ -- Extends 0004's keys_issued_guard(): identity, lineage AND environment are
31
+ -- immutable once a row is inserted.
32
+ create or replace function public.keys_issued_guard() returns trigger
33
+ language plpgsql
34
+ set search_path = pg_catalog, public, pg_temp
35
+ as $$
36
+ begin
37
+ if tg_op in ('DELETE', 'TRUNCATE') then
38
+ raise exception 'keys_issued_credentials: delete and truncate refused';
39
+ end if;
40
+ if tg_op = 'UPDATE' then
41
+ if new.id is distinct from old.id or new.issued_by_id is distinct from old.issued_by_id
42
+ or new.key_prefix is distinct from old.key_prefix
43
+ or new.environment is distinct from old.environment then
44
+ raise exception 'keys_issued_credentials: identity, lineage and environment are immutable';
45
+ end if;
46
+ if old.revoked_at is not null and new.revoked_at is distinct from old.revoked_at then
47
+ raise exception 'keys_issued_credentials: revocation is permanent';
48
+ end if;
49
+ end if;
50
+ return new;
51
+ end
52
+ $$;
@@ -0,0 +1,26 @@
1
+ -- #46: last-used and usage tracking on every issued credential, so an admin
2
+ -- UI (manage) can tell which issued keys are live versus stale. Additive; do
3
+ -- not edit copied migrations.
4
+ --
5
+ -- Neither column is part of SignableRow (worker-contract.ts) -- unsigned,
6
+ -- same footing as environment/idempotency_key/created_at (0005) -- and, per
7
+ -- keys_issued_guard() below, is NOT frozen the way those are: check() writes
8
+ -- both on every successful verification, so they must stay ordinarily
9
+ -- updatable rather than joining the identity/lineage/environment immutable
10
+ -- set.
11
+ alter table keys_issued_credentials
12
+ add column if not exists last_used_at timestamptz,
13
+ add column if not exists use_count bigint not null default 0;
14
+
15
+ do $$
16
+ begin
17
+ if not exists (
18
+ select 1 from pg_constraint
19
+ where conname = 'keys_issued_credentials_use_count_check'
20
+ ) then
21
+ alter table keys_issued_credentials
22
+ add constraint keys_issued_credentials_use_count_check
23
+ check (use_count >= 0);
24
+ end if;
25
+ end
26
+ $$;
@@ -0,0 +1,20 @@
1
+ -- #45: a per-issued-credential rate limit window, backing
2
+ -- `createPostgresRateLimiter` (`src/issued/ratelimit.ts`). Additive; do not
3
+ -- edit copied migrations.
4
+ --
5
+ -- One bounded row per credential, atomically reset each window by the same
6
+ -- upsert shape `packages/worker/src/ratelimit.ts`'s D1
7
+ -- `host_rate_limit_windows` uses for the host's own service credential --
8
+ -- this table is the same idea one level down, keyed by the END USER's
9
+ -- issued credential id rather than the host's.
10
+ --
11
+ -- No foreign key to keys_issued_credentials: a row here outlives a revoked
12
+ -- or even (in principle) a since-deleted credential without orphaning a
13
+ -- constraint, and check() only ever looks one up by an id it already
14
+ -- verified against a signed row.
15
+ create table if not exists keys_issued_rate_limit_windows (
16
+ credential_id text not null primary key,
17
+ window_start bigint not null,
18
+ count integer not null,
19
+ constraint keys_issued_rate_limit_windows_count_check check (count > 0)
20
+ );