@aooth/auth 0.1.85 → 0.2.1

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 (35) hide show
  1. package/dist/atscript-db.cjs +80 -4
  2. package/dist/atscript-db.d.cts +51 -10
  3. package/dist/atscript-db.d.mts +51 -10
  4. package/dist/atscript-db.mjs +79 -5
  5. package/dist/{auth-credential-CLAQgjCS.d.mts → auth-credential-CjCgZv7n.d.mts} +106 -9
  6. package/dist/{auth-credential-GRAK230V.d.cts → auth-credential-UV3sJ-lt.d.cts} +106 -9
  7. package/dist/authz.d.cts +2 -2
  8. package/dist/authz.d.mts +2 -2
  9. package/dist/client.cjs +25 -12
  10. package/dist/client.d.cts +59 -13
  11. package/dist/client.d.mts +59 -13
  12. package/dist/client.mjs +25 -12
  13. package/dist/{clock-CyjqzLxc.d.cts → clock-CzAaCoZ5.d.cts} +7 -0
  14. package/dist/{clock-CyjqzLxc.d.mts → clock-CzAaCoZ5.d.mts} +7 -0
  15. package/dist/{dynamic-client-store-BF4nXMK2.d.mts → dynamic-client-store-B7EnHuRp.d.cts} +2 -2
  16. package/dist/{dynamic-client-store-HLfcl2FJ.d.cts → dynamic-client-store-BifZLGkT.d.mts} +2 -2
  17. package/dist/index.cjs +351 -128
  18. package/dist/index.d.cts +26 -4
  19. package/dist/index.d.mts +26 -4
  20. package/dist/index.mjs +328 -106
  21. package/dist/{payload-HPgyPiek.cjs → payload-C1cQW7p_.cjs} +27 -0
  22. package/dist/{payload-DP5zRiXT.mjs → payload-DDlf38B-.mjs} +22 -1
  23. package/dist/redis.cjs +18 -6
  24. package/dist/redis.d.cts +19 -4
  25. package/dist/redis.d.mts +19 -4
  26. package/dist/redis.mjs +18 -6
  27. package/dist/store-BaFYDHxn.d.cts +69 -0
  28. package/dist/store-h-bLOAaS.d.mts +69 -0
  29. package/package.json +9 -9
  30. package/src/atscript-db/auth-code.as.d.ts +1 -1
  31. package/src/atscript-db/auth-credential.as.d.ts +1 -1
  32. package/src/atscript-db/dynamic-client.as.d.ts +1 -1
  33. package/src/atscript-db/pending-authorization.as.d.ts +1 -1
  34. package/dist/store-CVD1nd2j.d.mts +0 -41
  35. package/dist/store-ClQnA8yh.d.cts +0 -41
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_payload = require("./payload-C1cQW7p_.cjs");
2
3
  const require_clock = require("./clock-Bl-H3eqE.cjs");
3
- const require_payload = require("./payload-HPgyPiek.cjs");
4
4
  const require_dynamic_client_store = require("./dynamic-client-store-DykM9QOT.cjs");
5
5
  let node_crypto = require("node:crypto");
6
6
  //#region src/atscript-db/authz-stores.ts
@@ -221,6 +221,51 @@ function rowToDynamicClient(row) {
221
221
  //#endregion
222
222
  //#region src/atscript-db/index.ts
223
223
  /**
224
+ * Metadata keys that carry per-token authority — losing them on a store
225
+ * without a metadata column would silently widen what the token can do.
226
+ */
227
+ const AUTHORITY_METADATA_KEYS = [
228
+ "accessTtl",
229
+ "refreshRotation",
230
+ "rotationGraceMs",
231
+ "credentialKind",
232
+ "authzClientId"
233
+ ];
234
+ const specCache = /* @__PURE__ */ new WeakMap();
235
+ /**
236
+ * Find the credential-metadata column of a credential model: the field
237
+ * annotated `@aooth.auth.metadata` (registered by `arbacPlugin`) that also
238
+ * carries `@db.json`. An annotated field without `@db.json` resolves to
239
+ * `undefined` with a warning; more than one annotated field throws. Cached
240
+ * per model.
241
+ */
242
+ function getAoothCredentialMetadataSpec(credentialType) {
243
+ const typed = credentialType;
244
+ const cacheable = typed !== null && typeof typed === "object";
245
+ if (cacheable) {
246
+ const cached = specCache.get(typed);
247
+ if (cached) return cached;
248
+ }
249
+ const spec = {
250
+ metadataField: void 0,
251
+ warnings: []
252
+ };
253
+ const def = typed?.type;
254
+ if (def?.kind === "object" && def.props) {
255
+ const candidates = [];
256
+ for (const [field, prop] of def.props) if (prop.metadata?.get("aooth.auth.metadata")) candidates.push({
257
+ field,
258
+ json: Boolean(prop.metadata.get("db.json"))
259
+ });
260
+ if (candidates.length > 1) throw new Error(`getAoothCredentialMetadataSpec: multiple @aooth.auth.metadata fields declared (${candidates.map((c) => c.field).join(", ")}) — keep the annotation on exactly one field.`);
261
+ const [only] = candidates;
262
+ if (only?.json) spec.metadataField = only.field;
263
+ else if (only) spec.warnings.push(`@aooth.auth.metadata on field "${only.field}" has no @db.json — credential metadata will not be persisted. Add @db.json to the field.`);
264
+ }
265
+ if (cacheable) specCache.set(typed, spec);
266
+ return spec;
267
+ }
268
+ /**
224
269
  * atscript-db-backed `CredentialStore`.
225
270
  *
226
271
  * - `persist` generates a random UUID token id, inserts a row.
@@ -236,16 +281,44 @@ function rowToDynamicClient(row) {
236
281
  var CredentialStoreAtscriptDb = class {
237
282
  table;
238
283
  metadataField;
284
+ optedOut;
285
+ warn;
286
+ warnedDroppedMetadata = false;
239
287
  constructor(opts) {
240
288
  this.table = opts.table;
241
- this.metadataField = opts.metadataField;
289
+ this.warn = opts.onWarning ?? ((message) => console.warn(`[aooth] ${message}`));
290
+ this.optedOut = opts.metadataField === false;
291
+ if (typeof opts.metadataField === "string") this.metadataField = opts.metadataField;
292
+ else if (!this.optedOut && opts.table.type !== void 0) {
293
+ const spec = getAoothCredentialMetadataSpec(opts.table.type);
294
+ for (const warning of spec.warnings) this.warn(warning);
295
+ this.metadataField = spec.metadataField;
296
+ }
297
+ }
298
+ /**
299
+ * No metadata column: refuse a state whose metadata carries per-token
300
+ * authority (fail closed); drop the rest with a one-time warning.
301
+ */
302
+ checkMetadata(state) {
303
+ if (this.metadataField !== void 0 || state.metadata === void 0) return;
304
+ const meta = state.metadata;
305
+ const lost = AUTHORITY_METADATA_KEYS.filter((k) => meta[k] !== void 0);
306
+ if (lost.length > 0) throw new require_payload.AuthError("INVALID_CONFIG", `CredentialStoreAtscriptDb has no metadata column, so this credential's restrictions (${lost.join(", ")}) would be lost. Declare an @aooth.auth.metadata @db.json field on the credential model (or pass metadataField).`);
307
+ if (!this.optedOut && !this.warnedDroppedMetadata) {
308
+ this.warnedDroppedMetadata = true;
309
+ this.warn("CredentialStoreAtscriptDb has no metadata column — credential metadata (ip, user agent, label…) is not persisted. Declare an @aooth.auth.metadata @db.json field on the credential model, or pass metadataField: false to silence this.");
310
+ }
242
311
  }
243
312
  async persist(state, ttl) {
244
313
  const token = (0, node_crypto.randomUUID)();
245
- const expiresAt = typeof ttl === "number" ? Date.now() + ttl : state.expiresAt;
246
- await this.table.insertOne(stateToRow(state, token, expiresAt, this.metadataField));
314
+ await this.persistAs(token, state, ttl);
247
315
  return token;
248
316
  }
317
+ async persistAs(id, state, ttl) {
318
+ this.checkMetadata(state);
319
+ const expiresAt = typeof ttl === "number" ? Date.now() + ttl : state.expiresAt;
320
+ await this.table.insertOne(stateToRow(state, id, expiresAt, this.metadataField));
321
+ }
249
322
  async retrieve(token) {
250
323
  const row = await this.table.findOne({ filter: { token } });
251
324
  if (!row) return null;
@@ -262,6 +335,7 @@ var CredentialStoreAtscriptDb = class {
262
335
  return state;
263
336
  }
264
337
  async update(token, state) {
338
+ this.checkMetadata(state);
265
339
  if (!await this.table.findOne({ filter: { token } })) return token;
266
340
  if (state.expiresAt <= Date.now()) {
267
341
  await this.revoke(token);
@@ -366,7 +440,9 @@ function rowToState(row, metadataField) {
366
440
  return state;
367
441
  }
368
442
  //#endregion
443
+ exports.AUTHORITY_METADATA_KEYS = AUTHORITY_METADATA_KEYS;
369
444
  exports.AuthCodeStoreAtscriptDb = AuthCodeStoreAtscriptDb;
370
445
  exports.CredentialStoreAtscriptDb = CredentialStoreAtscriptDb;
371
446
  exports.DynamicClientStoreAtscriptDb = DynamicClientStoreAtscriptDb;
372
447
  exports.PendingAuthorizationStoreAtscriptDb = PendingAuthorizationStoreAtscriptDb;
448
+ exports.getAoothCredentialMetadataSpec = getAoothCredentialMetadataSpec;
@@ -1,5 +1,5 @@
1
- import { c as CredentialSuccessorRef, r as CredentialStore, s as CredentialState, t as Clock } from "./clock-CyjqzLxc.cjs";
2
- import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-HLfcl2FJ.cjs";
1
+ import { c as CredentialSuccessorRef, r as CredentialStore, s as CredentialState, t as Clock } from "./clock-CzAaCoZ5.cjs";
2
+ import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-B7EnHuRp.cjs";
3
3
  //#region src/atscript-db/authz-stores.d.ts
4
4
  /**
5
5
  * atscript-db-backed durable implementations of the two short-lived
@@ -263,19 +263,51 @@ interface AuthCredentialTable<TPayload extends object = object> {
263
263
  token: string;
264
264
  lastSeenAt: number;
265
265
  }): Promise<unknown>;
266
+ /**
267
+ * The table's annotated model (atscript-db's `table.type`). Read once to
268
+ * find the `@aooth.auth.metadata` column when `metadataField` is not given.
269
+ */
270
+ readonly type?: unknown;
266
271
  }
267
272
  interface CredentialStoreAtscriptDbOptions<TPayload extends object> {
268
273
  table: AuthCredentialTable<TPayload>;
269
274
  /**
270
- * Name of the consumer's `@aooth.auth.metadata`-annotated column — the
271
- * fully-typed `@db.json` field declared on their `extends AoothAuthCredential`
272
- * model that persists the envelope's `metadata`. Resolved at boot by
273
- * `getAoothCredentialMetadataSpec` (`@aooth/arbac-moost/atscript`) and
274
- * threaded here as plain config — same pattern as `UserStore.handleFields`.
275
- * Absent → metadata is not persisted/read by this store.
275
+ * Column that persists the envelope's `metadata` — the consumer's
276
+ * `@aooth.auth.metadata` + `@db.json` field on their `extends
277
+ * AoothAuthCredential` model. Default: resolved automatically from
278
+ * `table.type` (see {@link getAoothCredentialMetadataSpec}). `false` = no
279
+ * metadata column (explicit opt-out).
280
+ *
281
+ * Without a column the store FAILS CLOSED: persisting a credential whose
282
+ * metadata carries a per-token restriction (`accessTtl`, `refreshRotation`,
283
+ * `rotationGraceMs`, `credentialKind`, `authzClientId`) throws `AuthError('INVALID_CONFIG')` — dropping
284
+ * it would let e.g. a fixed-lifetime token family slide forever. Other
285
+ * metadata (ip, user agent, label…) is dropped with a one-time warning.
276
286
  */
277
- metadataField?: string;
287
+ metadataField?: string | false;
288
+ /** Receives configuration warnings. Default: `console.warn`. */
289
+ onWarning?: (message: string) => void;
290
+ }
291
+ /**
292
+ * Metadata keys that carry per-token authority — losing them on a store
293
+ * without a metadata column would silently widen what the token can do.
294
+ */
295
+ declare const AUTHORITY_METADATA_KEYS: readonly ["accessTtl", "refreshRotation", "rotationGraceMs", "credentialKind", "authzClientId"];
296
+ /** Resolved credential-metadata column of a credential model (see {@link getAoothCredentialMetadataSpec}). */
297
+ interface AoothCredentialMetadataSpec {
298
+ /** The `@aooth.auth.metadata` + `@db.json` field, or `undefined`. */
299
+ metadataField: string | undefined;
300
+ /** Non-fatal misconfiguration notes (an annotated field without `@db.json`). */
301
+ warnings: string[];
278
302
  }
303
+ /**
304
+ * Find the credential-metadata column of a credential model: the field
305
+ * annotated `@aooth.auth.metadata` (registered by `arbacPlugin`) that also
306
+ * carries `@db.json`. An annotated field without `@db.json` resolves to
307
+ * `undefined` with a warning; more than one annotated field throws. Cached
308
+ * per model.
309
+ */
310
+ declare function getAoothCredentialMetadataSpec(credentialType: unknown): AoothCredentialMetadataSpec;
279
311
  /**
280
312
  * atscript-db-backed `CredentialStore`.
281
313
  *
@@ -292,8 +324,17 @@ interface CredentialStoreAtscriptDbOptions<TPayload extends object> {
292
324
  declare class CredentialStoreAtscriptDb<TPayload extends object = object> implements CredentialStore<TPayload> {
293
325
  private readonly table;
294
326
  private readonly metadataField;
327
+ private readonly optedOut;
328
+ private readonly warn;
329
+ private warnedDroppedMetadata;
295
330
  constructor(opts: CredentialStoreAtscriptDbOptions<TPayload>);
331
+ /**
332
+ * No metadata column: refuse a state whose metadata carries per-token
333
+ * authority (fail closed); drop the rest with a one-time warning.
334
+ */
335
+ private checkMetadata;
296
336
  persist(state: CredentialState & TPayload, ttl?: number): Promise<string>;
337
+ persistAs(id: string, state: CredentialState & TPayload, ttl?: number): Promise<void>;
297
338
  retrieve(token: string): Promise<(CredentialState & TPayload) | null>;
298
339
  consume(token: string): Promise<(CredentialState & TPayload) | null>;
299
340
  update(token: string, state: CredentialState & TPayload): Promise<string>;
@@ -305,4 +346,4 @@ declare class CredentialStoreAtscriptDb<TPayload extends object = object> implem
305
346
  }>>;
306
347
  }
307
348
  //#endregion
308
- export { AuthCodeRow, AuthCodeStoreAtscriptDb, AuthCodeStoreAtscriptDbOptions, AuthCodeTable, AuthCredentialRow, AuthCredentialTable, CredentialStoreAtscriptDb, DynamicClientRow, DynamicClientStoreAtscriptDb, DynamicClientStoreAtscriptDbOptions, DynamicClientTable, PendingAuthorizationRow, PendingAuthorizationStoreAtscriptDb, PendingAuthorizationStoreAtscriptDbOptions, PendingAuthorizationTable };
349
+ export { AUTHORITY_METADATA_KEYS, AoothCredentialMetadataSpec, AuthCodeRow, AuthCodeStoreAtscriptDb, AuthCodeStoreAtscriptDbOptions, AuthCodeTable, AuthCredentialRow, AuthCredentialTable, CredentialStoreAtscriptDb, DynamicClientRow, DynamicClientStoreAtscriptDb, DynamicClientStoreAtscriptDbOptions, DynamicClientTable, PendingAuthorizationRow, PendingAuthorizationStoreAtscriptDb, PendingAuthorizationStoreAtscriptDbOptions, PendingAuthorizationTable, getAoothCredentialMetadataSpec };
@@ -1,5 +1,5 @@
1
- import { c as CredentialSuccessorRef, r as CredentialStore, s as CredentialState, t as Clock } from "./clock-CyjqzLxc.mjs";
2
- import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-BF4nXMK2.mjs";
1
+ import { c as CredentialSuccessorRef, r as CredentialStore, s as CredentialState, t as Clock } from "./clock-CzAaCoZ5.mjs";
2
+ import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-BifZLGkT.mjs";
3
3
  //#region src/atscript-db/authz-stores.d.ts
4
4
  /**
5
5
  * atscript-db-backed durable implementations of the two short-lived
@@ -263,19 +263,51 @@ interface AuthCredentialTable<TPayload extends object = object> {
263
263
  token: string;
264
264
  lastSeenAt: number;
265
265
  }): Promise<unknown>;
266
+ /**
267
+ * The table's annotated model (atscript-db's `table.type`). Read once to
268
+ * find the `@aooth.auth.metadata` column when `metadataField` is not given.
269
+ */
270
+ readonly type?: unknown;
266
271
  }
267
272
  interface CredentialStoreAtscriptDbOptions<TPayload extends object> {
268
273
  table: AuthCredentialTable<TPayload>;
269
274
  /**
270
- * Name of the consumer's `@aooth.auth.metadata`-annotated column — the
271
- * fully-typed `@db.json` field declared on their `extends AoothAuthCredential`
272
- * model that persists the envelope's `metadata`. Resolved at boot by
273
- * `getAoothCredentialMetadataSpec` (`@aooth/arbac-moost/atscript`) and
274
- * threaded here as plain config — same pattern as `UserStore.handleFields`.
275
- * Absent → metadata is not persisted/read by this store.
275
+ * Column that persists the envelope's `metadata` — the consumer's
276
+ * `@aooth.auth.metadata` + `@db.json` field on their `extends
277
+ * AoothAuthCredential` model. Default: resolved automatically from
278
+ * `table.type` (see {@link getAoothCredentialMetadataSpec}). `false` = no
279
+ * metadata column (explicit opt-out).
280
+ *
281
+ * Without a column the store FAILS CLOSED: persisting a credential whose
282
+ * metadata carries a per-token restriction (`accessTtl`, `refreshRotation`,
283
+ * `rotationGraceMs`, `credentialKind`, `authzClientId`) throws `AuthError('INVALID_CONFIG')` — dropping
284
+ * it would let e.g. a fixed-lifetime token family slide forever. Other
285
+ * metadata (ip, user agent, label…) is dropped with a one-time warning.
276
286
  */
277
- metadataField?: string;
287
+ metadataField?: string | false;
288
+ /** Receives configuration warnings. Default: `console.warn`. */
289
+ onWarning?: (message: string) => void;
290
+ }
291
+ /**
292
+ * Metadata keys that carry per-token authority — losing them on a store
293
+ * without a metadata column would silently widen what the token can do.
294
+ */
295
+ declare const AUTHORITY_METADATA_KEYS: readonly ["accessTtl", "refreshRotation", "rotationGraceMs", "credentialKind", "authzClientId"];
296
+ /** Resolved credential-metadata column of a credential model (see {@link getAoothCredentialMetadataSpec}). */
297
+ interface AoothCredentialMetadataSpec {
298
+ /** The `@aooth.auth.metadata` + `@db.json` field, or `undefined`. */
299
+ metadataField: string | undefined;
300
+ /** Non-fatal misconfiguration notes (an annotated field without `@db.json`). */
301
+ warnings: string[];
278
302
  }
303
+ /**
304
+ * Find the credential-metadata column of a credential model: the field
305
+ * annotated `@aooth.auth.metadata` (registered by `arbacPlugin`) that also
306
+ * carries `@db.json`. An annotated field without `@db.json` resolves to
307
+ * `undefined` with a warning; more than one annotated field throws. Cached
308
+ * per model.
309
+ */
310
+ declare function getAoothCredentialMetadataSpec(credentialType: unknown): AoothCredentialMetadataSpec;
279
311
  /**
280
312
  * atscript-db-backed `CredentialStore`.
281
313
  *
@@ -292,8 +324,17 @@ interface CredentialStoreAtscriptDbOptions<TPayload extends object> {
292
324
  declare class CredentialStoreAtscriptDb<TPayload extends object = object> implements CredentialStore<TPayload> {
293
325
  private readonly table;
294
326
  private readonly metadataField;
327
+ private readonly optedOut;
328
+ private readonly warn;
329
+ private warnedDroppedMetadata;
295
330
  constructor(opts: CredentialStoreAtscriptDbOptions<TPayload>);
331
+ /**
332
+ * No metadata column: refuse a state whose metadata carries per-token
333
+ * authority (fail closed); drop the rest with a one-time warning.
334
+ */
335
+ private checkMetadata;
296
336
  persist(state: CredentialState & TPayload, ttl?: number): Promise<string>;
337
+ persistAs(id: string, state: CredentialState & TPayload, ttl?: number): Promise<void>;
297
338
  retrieve(token: string): Promise<(CredentialState & TPayload) | null>;
298
339
  consume(token: string): Promise<(CredentialState & TPayload) | null>;
299
340
  update(token: string, state: CredentialState & TPayload): Promise<string>;
@@ -305,4 +346,4 @@ declare class CredentialStoreAtscriptDb<TPayload extends object = object> implem
305
346
  }>>;
306
347
  }
307
348
  //#endregion
308
- export { AuthCodeRow, AuthCodeStoreAtscriptDb, AuthCodeStoreAtscriptDbOptions, AuthCodeTable, AuthCredentialRow, AuthCredentialTable, CredentialStoreAtscriptDb, DynamicClientRow, DynamicClientStoreAtscriptDb, DynamicClientStoreAtscriptDbOptions, DynamicClientTable, PendingAuthorizationRow, PendingAuthorizationStoreAtscriptDb, PendingAuthorizationStoreAtscriptDbOptions, PendingAuthorizationTable };
349
+ export { AUTHORITY_METADATA_KEYS, AoothCredentialMetadataSpec, AuthCodeRow, AuthCodeStoreAtscriptDb, AuthCodeStoreAtscriptDbOptions, AuthCodeTable, AuthCredentialRow, AuthCredentialTable, CredentialStoreAtscriptDb, DynamicClientRow, DynamicClientStoreAtscriptDb, DynamicClientStoreAtscriptDbOptions, DynamicClientTable, PendingAuthorizationRow, PendingAuthorizationStoreAtscriptDb, PendingAuthorizationStoreAtscriptDbOptions, PendingAuthorizationTable, getAoothCredentialMetadataSpec };
@@ -1,5 +1,5 @@
1
+ import { n as AuthError, t as credentialPayloadOf } from "./payload-DDlf38B-.mjs";
1
2
  import { t as defaultClock } from "./clock-Bdsep_1j.mjs";
2
- import { t as credentialPayloadOf } from "./payload-DP5zRiXT.mjs";
3
3
  import { r as AuthCodeStore, s as PendingAuthorizationStore, t as DynamicClientStore } from "./dynamic-client-store-B1JwFHdP.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  //#region src/atscript-db/authz-stores.ts
@@ -220,6 +220,51 @@ function rowToDynamicClient(row) {
220
220
  //#endregion
221
221
  //#region src/atscript-db/index.ts
222
222
  /**
223
+ * Metadata keys that carry per-token authority — losing them on a store
224
+ * without a metadata column would silently widen what the token can do.
225
+ */
226
+ const AUTHORITY_METADATA_KEYS = [
227
+ "accessTtl",
228
+ "refreshRotation",
229
+ "rotationGraceMs",
230
+ "credentialKind",
231
+ "authzClientId"
232
+ ];
233
+ const specCache = /* @__PURE__ */ new WeakMap();
234
+ /**
235
+ * Find the credential-metadata column of a credential model: the field
236
+ * annotated `@aooth.auth.metadata` (registered by `arbacPlugin`) that also
237
+ * carries `@db.json`. An annotated field without `@db.json` resolves to
238
+ * `undefined` with a warning; more than one annotated field throws. Cached
239
+ * per model.
240
+ */
241
+ function getAoothCredentialMetadataSpec(credentialType) {
242
+ const typed = credentialType;
243
+ const cacheable = typed !== null && typeof typed === "object";
244
+ if (cacheable) {
245
+ const cached = specCache.get(typed);
246
+ if (cached) return cached;
247
+ }
248
+ const spec = {
249
+ metadataField: void 0,
250
+ warnings: []
251
+ };
252
+ const def = typed?.type;
253
+ if (def?.kind === "object" && def.props) {
254
+ const candidates = [];
255
+ for (const [field, prop] of def.props) if (prop.metadata?.get("aooth.auth.metadata")) candidates.push({
256
+ field,
257
+ json: Boolean(prop.metadata.get("db.json"))
258
+ });
259
+ if (candidates.length > 1) throw new Error(`getAoothCredentialMetadataSpec: multiple @aooth.auth.metadata fields declared (${candidates.map((c) => c.field).join(", ")}) — keep the annotation on exactly one field.`);
260
+ const [only] = candidates;
261
+ if (only?.json) spec.metadataField = only.field;
262
+ else if (only) spec.warnings.push(`@aooth.auth.metadata on field "${only.field}" has no @db.json — credential metadata will not be persisted. Add @db.json to the field.`);
263
+ }
264
+ if (cacheable) specCache.set(typed, spec);
265
+ return spec;
266
+ }
267
+ /**
223
268
  * atscript-db-backed `CredentialStore`.
224
269
  *
225
270
  * - `persist` generates a random UUID token id, inserts a row.
@@ -235,16 +280,44 @@ function rowToDynamicClient(row) {
235
280
  var CredentialStoreAtscriptDb = class {
236
281
  table;
237
282
  metadataField;
283
+ optedOut;
284
+ warn;
285
+ warnedDroppedMetadata = false;
238
286
  constructor(opts) {
239
287
  this.table = opts.table;
240
- this.metadataField = opts.metadataField;
288
+ this.warn = opts.onWarning ?? ((message) => console.warn(`[aooth] ${message}`));
289
+ this.optedOut = opts.metadataField === false;
290
+ if (typeof opts.metadataField === "string") this.metadataField = opts.metadataField;
291
+ else if (!this.optedOut && opts.table.type !== void 0) {
292
+ const spec = getAoothCredentialMetadataSpec(opts.table.type);
293
+ for (const warning of spec.warnings) this.warn(warning);
294
+ this.metadataField = spec.metadataField;
295
+ }
296
+ }
297
+ /**
298
+ * No metadata column: refuse a state whose metadata carries per-token
299
+ * authority (fail closed); drop the rest with a one-time warning.
300
+ */
301
+ checkMetadata(state) {
302
+ if (this.metadataField !== void 0 || state.metadata === void 0) return;
303
+ const meta = state.metadata;
304
+ const lost = AUTHORITY_METADATA_KEYS.filter((k) => meta[k] !== void 0);
305
+ if (lost.length > 0) throw new AuthError("INVALID_CONFIG", `CredentialStoreAtscriptDb has no metadata column, so this credential's restrictions (${lost.join(", ")}) would be lost. Declare an @aooth.auth.metadata @db.json field on the credential model (or pass metadataField).`);
306
+ if (!this.optedOut && !this.warnedDroppedMetadata) {
307
+ this.warnedDroppedMetadata = true;
308
+ this.warn("CredentialStoreAtscriptDb has no metadata column — credential metadata (ip, user agent, label…) is not persisted. Declare an @aooth.auth.metadata @db.json field on the credential model, or pass metadataField: false to silence this.");
309
+ }
241
310
  }
242
311
  async persist(state, ttl) {
243
312
  const token = randomUUID();
244
- const expiresAt = typeof ttl === "number" ? Date.now() + ttl : state.expiresAt;
245
- await this.table.insertOne(stateToRow(state, token, expiresAt, this.metadataField));
313
+ await this.persistAs(token, state, ttl);
246
314
  return token;
247
315
  }
316
+ async persistAs(id, state, ttl) {
317
+ this.checkMetadata(state);
318
+ const expiresAt = typeof ttl === "number" ? Date.now() + ttl : state.expiresAt;
319
+ await this.table.insertOne(stateToRow(state, id, expiresAt, this.metadataField));
320
+ }
248
321
  async retrieve(token) {
249
322
  const row = await this.table.findOne({ filter: { token } });
250
323
  if (!row) return null;
@@ -261,6 +334,7 @@ var CredentialStoreAtscriptDb = class {
261
334
  return state;
262
335
  }
263
336
  async update(token, state) {
337
+ this.checkMetadata(state);
264
338
  if (!await this.table.findOne({ filter: { token } })) return token;
265
339
  if (state.expiresAt <= Date.now()) {
266
340
  await this.revoke(token);
@@ -365,4 +439,4 @@ function rowToState(row, metadataField) {
365
439
  return state;
366
440
  }
367
441
  //#endregion
368
- export { AuthCodeStoreAtscriptDb, CredentialStoreAtscriptDb, DynamicClientStoreAtscriptDb, PendingAuthorizationStoreAtscriptDb };
442
+ export { AUTHORITY_METADATA_KEYS, AuthCodeStoreAtscriptDb, CredentialStoreAtscriptDb, DynamicClientStoreAtscriptDb, PendingAuthorizationStoreAtscriptDb, getAoothCredentialMetadataSpec };
@@ -1,4 +1,4 @@
1
- import { a as AuthContext, d as RefreshConfig, f as RefreshResult, i as DenylistStore, l as EnrichedSession, m as SessionInfo, o as CredentialMetadata, p as SessionEnricher, r as CredentialStore, s as CredentialState, t as Clock, u as IssueResult } from "./clock-CyjqzLxc.mjs";
1
+ import { a as AuthContext, d as RefreshConfig, f as RefreshResult, i as DenylistStore, l as EnrichedSession, m as SessionInfo, o as CredentialMetadata, p as SessionEnricher, r as CredentialStore, s as CredentialState, t as Clock, u as IssueResult } from "./clock-CzAaCoZ5.mjs";
2
2
  //#region src/credential/auth-credential.d.ts
3
3
  interface AuthCredentialOptions<TPayload extends object = object> {
4
4
  /** Pluggable credential store (Memory, JWT, Encapsulated, ...). */
@@ -48,6 +48,43 @@ interface AuthCredentialOptions<TPayload extends object = object> {
48
48
  ttlMs: number;
49
49
  max?: number;
50
50
  };
51
+ /**
52
+ * How tokens are minted and stored. Both options need a store with
53
+ * `persistAs` (memory, Redis, atscript-db — not the stateless JWT /
54
+ * encapsulated stores, whose token IS the state).
55
+ */
56
+ tokens?: {
57
+ /**
58
+ * Store a SHA-256 of each token instead of the token itself, so a
59
+ * database / backup / replica read yields no usable session, refresh token
60
+ * or PAT. The successor pair kept on a rotated refresh row is encrypted
61
+ * with a key derived from that refresh token (only its holder can read it
62
+ * back during the grace window), and `parentCredentialId` holds the hash.
63
+ * Tokens become 256-bit random strings unless `generate` is given.
64
+ * - `true` — hash every token; rows written before are not found (a
65
+ * one-time sign-out of existing sessions).
66
+ * - `'migrate'` — also look up the token itself when its hash is not
67
+ * found, so existing sessions keep working; a legacy refresh token is
68
+ * re-issued hashed on its next rotation. Switch to `true` once the
69
+ * longest refresh lifetime has passed.
70
+ * Default `false`.
71
+ */
72
+ hashAtRest?: boolean | "migrate";
73
+ /**
74
+ * Token generator (e.g. to add a recognisable prefix). Must return at
75
+ * least 128 bits of randomness — the stored SHA-256 is only as strong as
76
+ * the token it hashes. Default: 256 random bits, base64url.
77
+ */
78
+ generate?: () => string;
79
+ /**
80
+ * `'migrate'` only: which presented tokens may be looked up as-is (rows
81
+ * written before hashing). Default: the `randomUUID` shape the bundled
82
+ * stores minted. Pass a predicate when earlier tokens came from a custom
83
+ * `generate`. A 64-hex string (the shape of a stored hash) is never looked
84
+ * up as-is, so a value read from the database cannot be replayed as a token.
85
+ */
86
+ isLegacyToken?: (token: string) => boolean;
87
+ };
51
88
  /** Optional clock for testability. */
52
89
  clock?: Clock;
53
90
  }
@@ -166,8 +203,11 @@ declare class AuthCredential<TPayload extends object = object> {
166
203
  private readonly consumedRefreshes;
167
204
  /** Map size at which `consumedRefreshes` next sweeps its expired entries. */
168
205
  private consumedSweepAt;
169
- /** Opt-in validated-state cache (`validateCache`). */
206
+ /** Opt-in validated-state cache (`validateCache`), keyed by store key. */
170
207
  private readonly validated?;
208
+ private readonly hashAtRest;
209
+ private readonly generateToken?;
210
+ private readonly isLegacyToken;
171
211
  constructor(opts: AuthCredentialOptions<TPayload>);
172
212
  issue(userId: string, options?: IssueOptions<TPayload>): Promise<IssueResult>;
173
213
  validate(accessToken: string): Promise<AuthContext<TPayload> | null>;
@@ -176,6 +216,23 @@ declare class AuthCredential<TPayload extends object = object> {
176
216
  * it — both looked up concurrently (one round trip on remote stores).
177
217
  */
178
218
  private retrieveUnlessDenied;
219
+ /** The store key a token's row lives under: its SHA-256 when hashing, else the token. */
220
+ private keyOf;
221
+ /** `credentialId` (the token's SHA-256) of a stored row, from its store key. */
222
+ private fingerprintOfKey;
223
+ /** Persist a new credential; returns the token the client will hold. */
224
+ private put;
225
+ /**
226
+ * Look a token up: by its store key, and — under `hashAtRest: 'migrate'` —
227
+ * by the token itself for a row written before hashing was enabled.
228
+ */
229
+ private find;
230
+ /**
231
+ * `'migrate'`: may `token` be a row written before hashing, stored under
232
+ * the token itself? Never for a hash-shaped value — that is what a database
233
+ * read yields, and accepting it would turn a leaked row key into a session.
234
+ */
235
+ private mayBeLegacyKey;
179
236
  refresh(refreshToken: string, opts?: RefreshCallOptions<TPayload>): Promise<RefreshResult>;
180
237
  private refreshNone;
181
238
  /**
@@ -212,17 +269,16 @@ declare class AuthCredential<TPayload extends object = object> {
212
269
  */
213
270
  private rotateWithGrace;
214
271
  revoke(token: string): Promise<void>;
272
+ /** Revoke the row stored under `key` (a store key, as `listForUser` returns it). */
273
+ private revokeKey;
215
274
  revokeAllForUser(userId: string): Promise<number>;
216
275
  listForUser(userId: string): Promise<Array<AuthContext<TPayload>>>;
217
276
  /**
218
- * The session id for a credential: its stored `sessionId`, or the token
219
- * fingerprint for legacy rows predating sessionId (so they surface as
220
- * singleton sessions). The ONE place this fallback rule lives — shared by
221
- * `validate()`, `listForUser()`, and the session-family methods so "this
222
- * device" matching stays consistent across all of them.
277
+ * Session-grouping key for a stored credential entry (its store key
278
+ * attached): its stored `sessionId`, or the token fingerprint for legacy
279
+ * rows predating sessionId (so they surface as singleton sessions) — the
280
+ * same fallback `validate()` applies, so "this device" matching holds.
223
281
  */
224
- private sessionIdOf;
225
- /** Session-grouping key for a stored credential entry (token attached). */
226
282
  private sessionKeyOf;
227
283
  /**
228
284
  * List the user's active sessions, one row per token family (access +
@@ -235,6 +291,13 @@ declare class AuthCredential<TPayload extends object = object> {
235
291
  enrich?: SessionEnricher;
236
292
  kind?: string | string[];
237
293
  }): Promise<SessionInfo[] | EnrichedSession[]>;
294
+ /**
295
+ * Whether the store can enumerate a user's credentials — i.e. whether
296
+ * {@link listSessions}, {@link revokeSession} and {@link revokeOtherSessions}
297
+ * act at all. `false` for stateless stores (JWT, encapsulated), where those
298
+ * are no-ops and {@link revokeAllForUser} is the only bulk revocation.
299
+ */
300
+ get canEnumerateSessions(): boolean;
238
301
  /**
239
302
  * Revoke a single session — every token in its family (access + refresh +
240
303
  * rotations). No-op for stores that can't enumerate. Other sessions keep
@@ -247,6 +310,22 @@ declare class AuthCredential<TPayload extends object = object> {
247
310
  * (returns 0) for stores that can't enumerate.
248
311
  */
249
312
  revokeOtherSessions(userId: string, keepSessionId: string): Promise<number>;
313
+ /**
314
+ * Revoke every credential of `userId` whose session key matches, repeating
315
+ * list-then-delete until a listing finds no match; returns the distinct
316
+ * session keys revoked. No-op on stores that can't enumerate.
317
+ *
318
+ * Paired with the post-mint re-check in {@link assertStillLive}, this closes
319
+ * the race with refreshes in flight. A refresh re-reads the row it was
320
+ * minted from AFTER persisting its new rows, and revokes them if that row is
321
+ * gone. So a row surviving the final (empty) listing would have to be minted
322
+ * after that listing off a parent still alive after it — a parent that, not
323
+ * being listed, was itself minted after it, and so on down a chain that
324
+ * must start at a row that existed before the listing: a contradiction.
325
+ * Typically two passes (the second finds nothing); capped, failing loudly
326
+ * rather than spinning against a refresh loop.
327
+ */
328
+ private sweepUntilEmpty;
250
329
  /**
251
330
  * Derive a stable 32-byte key from this credential's underlying store secret,
252
331
  * domain-separated by `label`. Lets adjacent subsystems (e.g. workflow-state
@@ -265,6 +344,24 @@ declare class AuthCredential<TPayload extends object = object> {
265
344
  * rotated (keeping it valid through the grace window) instead of consuming it.
266
345
  */
267
346
  private issueRotatedPair;
347
+ /**
348
+ * Post-mint half of the revocation protocol (see {@link sweepUntilEmpty}): after
349
+ * a refresh persisted new credentials, the refresh row it was minted from
350
+ * must still exist. If a revocation deleted it meanwhile, the new
351
+ * credentials belong to a revoked session — revoke them and refuse.
352
+ * Stateful stores only: a stateless refresh consumed (or keeps) a
353
+ * self-contained token, and its revocation epoch already rejects a mint
354
+ * stamped before the revocation.
355
+ */
356
+ private assertStillLive;
357
+ /**
358
+ * Under `hashAtRest` the successor pair is stored encrypted with a key
359
+ * derived from the old refresh token — only a holder of that token (the
360
+ * grace-window re-presentation) can read the pair back.
361
+ */
362
+ private sealSuccessor;
363
+ /** Inverse of {@link sealSuccessor}; `undefined` when the pair cannot be opened. */
364
+ private openSuccessor;
268
365
  /** Amortized sweep of expired `consumedRefreshes` entries (each size doubling). */
269
366
  private sweepConsumedRefreshes;
270
367
  private lookupConsumedRefresh;