@smplcty/auth 0.6.4 → 2.0.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 (90) hide show
  1. package/README.md +187 -201
  2. package/dist/create-session.d.ts +10 -9
  3. package/dist/create-session.d.ts.map +1 -1
  4. package/dist/create-session.js +16 -18
  5. package/dist/create-session.js.map +1 -1
  6. package/dist/errors.d.ts +19 -4
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +23 -5
  9. package/dist/errors.js.map +1 -1
  10. package/dist/find-user-by-communication-method.d.ts.map +1 -1
  11. package/dist/find-user-by-communication-method.js +4 -0
  12. package/dist/find-user-by-communication-method.js.map +1 -1
  13. package/dist/get-user-role-names.d.ts.map +1 -1
  14. package/dist/get-user-role-names.js +2 -0
  15. package/dist/get-user-role-names.js.map +1 -1
  16. package/dist/index.d.ts +9 -5
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +12 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/internal/hash-token.d.ts +16 -0
  21. package/dist/internal/hash-token.d.ts.map +1 -0
  22. package/dist/internal/hash-token.js +21 -0
  23. package/dist/internal/hash-token.js.map +1 -0
  24. package/dist/methods/errors.d.ts +23 -0
  25. package/dist/methods/errors.d.ts.map +1 -0
  26. package/dist/methods/errors.js +28 -0
  27. package/dist/methods/errors.js.map +1 -0
  28. package/dist/methods/oidc/index.d.ts +92 -0
  29. package/dist/methods/oidc/index.d.ts.map +1 -0
  30. package/dist/methods/oidc/index.js +104 -0
  31. package/dist/methods/oidc/index.js.map +1 -0
  32. package/dist/methods/router.d.ts +19 -0
  33. package/dist/methods/router.d.ts.map +1 -0
  34. package/dist/methods/router.js +95 -0
  35. package/dist/methods/router.js.map +1 -0
  36. package/dist/methods/twilio/index.d.ts +44 -0
  37. package/dist/methods/twilio/index.d.ts.map +1 -0
  38. package/dist/methods/twilio/index.js +77 -0
  39. package/dist/methods/twilio/index.js.map +1 -0
  40. package/dist/methods/types.d.ts +106 -0
  41. package/dist/methods/types.d.ts.map +1 -0
  42. package/dist/methods/types.js +2 -0
  43. package/dist/methods/types.js.map +1 -0
  44. package/dist/revoke-session.d.ts +20 -15
  45. package/dist/revoke-session.d.ts.map +1 -1
  46. package/dist/revoke-session.js +66 -20
  47. package/dist/revoke-session.js.map +1 -1
  48. package/dist/scope/flat-tenant.d.ts +36 -0
  49. package/dist/scope/flat-tenant.d.ts.map +1 -0
  50. package/dist/scope/flat-tenant.js +60 -0
  51. package/dist/scope/flat-tenant.js.map +1 -0
  52. package/dist/set-helpers.d.ts +44 -53
  53. package/dist/set-helpers.d.ts.map +1 -1
  54. package/dist/set-helpers.js +67 -68
  55. package/dist/set-helpers.js.map +1 -1
  56. package/dist/touch-session.d.ts +13 -0
  57. package/dist/touch-session.d.ts.map +1 -0
  58. package/dist/touch-session.js +28 -0
  59. package/dist/touch-session.js.map +1 -0
  60. package/dist/types.d.ts +59 -18
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/validate-session.d.ts +15 -14
  63. package/dist/validate-session.d.ts.map +1 -1
  64. package/dist/validate-session.js +28 -27
  65. package/dist/validate-session.js.map +1 -1
  66. package/dist/with-service-context.d.ts +15 -12
  67. package/dist/with-service-context.d.ts.map +1 -1
  68. package/dist/with-service-context.js +34 -30
  69. package/dist/with-service-context.js.map +1 -1
  70. package/dist/with-session.d.ts +22 -16
  71. package/dist/with-session.d.ts.map +1 -1
  72. package/dist/with-session.js +67 -63
  73. package/dist/with-session.js.map +1 -1
  74. package/package.json +33 -2
  75. package/schema/functions/current_user_id.yaml +18 -0
  76. package/schema/functions/resolve_session.yaml +42 -23
  77. package/schema/post/0001-backfill-audit-by.sql +15 -0
  78. package/schema/tables/auth_domains.yaml +43 -0
  79. package/schema/tables/communication_channels.yaml +5 -1
  80. package/schema/tables/dev_otp_enrollments.yaml +1 -0
  81. package/schema/tables/roles.yaml +43 -7
  82. package/schema/tables/sessions.yaml +10 -0
  83. package/schema/tables/tenants.yaml +24 -1
  84. package/schema/tables/user_communication_methods.yaml +5 -1
  85. package/schema/tables/user_roles.yaml +1 -0
  86. package/schema/tables/users.yaml +27 -0
  87. package/dist/with-transaction.d.ts +0 -31
  88. package/dist/with-transaction.d.ts.map +0 -1
  89. package/dist/with-transaction.js +0 -49
  90. package/dist/with-transaction.js.map +0 -1
@@ -1,7 +1,5 @@
1
- import { randomUUID } from 'node:crypto';
2
1
  import { InvalidInputError } from './errors.js';
3
- const TS_SUFFIX = process.env['USE_AT_FOR_TIMESTAMPS'] !== 'false' ? '_at' : '';
4
- const CREATED_COL = `created${TS_SUFFIX}`;
2
+ import { generateToken, hashToken } from './internal/hash-token.js';
5
3
  const INSERT_SESSION = `
6
4
  INSERT INTO sessions (
7
5
  session_id,
@@ -26,10 +24,8 @@ const INSERT_SESSION = `
26
24
  $9
27
25
  )
28
26
  RETURNING
29
- session_id AS "sessionId",
30
- user_communication_method_id AS "_userCommunicationMethodId",
31
- ${CREATED_COL} AS "createdAt",
32
- expires_at AS "expiresAt"
27
+ created_at AS "createdAt",
28
+ expires_at AS "expiresAt"
33
29
  `;
34
30
  const SELECT_USER_ID = `
35
31
  SELECT user_id AS "userId"
@@ -39,16 +35,16 @@ const SELECT_USER_ID = `
39
35
  /**
40
36
  * Create a new session for an already-authenticated user.
41
37
  *
42
- * The caller is responsible for verifying the user's identity (via
43
- * Twilio Verify, OIDC callback, password check, or whatever) BEFORE
44
- * calling this function. `createSession` does not perform any
45
- * authentication of its own — it simply persists a session row and
46
- * returns the new session token.
38
+ * The caller is responsible for verifying the user's identity (via a
39
+ * `MethodHandler`, Twilio Verify, OIDC callback, password check, …)
40
+ * BEFORE calling this. `createSession` performs no authentication — it
41
+ * persists a session row and returns the new token.
47
42
  *
48
- * The session ID is generated server-side using `crypto.randomUUID()`
49
- * (122 bits of entropy). The expiration is computed server-side as
50
- * `now() + interval $ttl` so there is no clock skew between the app and
51
- * the database.
43
+ * A fresh opaque token (256 bits of entropy) is generated server-side;
44
+ * only its **SHA-256 hash** is stored, as the `sessions` primary key. The
45
+ * raw token is returned **once** in {@link Session.token} — hand it to the
46
+ * client and don't persist it. Expiration is computed server-side as
47
+ * `now() + interval $ttl` so there's no app/database clock skew.
52
48
  *
53
49
  * @example
54
50
  * ```ts
@@ -58,6 +54,7 @@ const SELECT_USER_ID = `
58
54
  * ip: req.ip,
59
55
  * geo: { country: 'US', region: 'CA' },
60
56
  * });
57
+ * setCookie('session', session.token); // raw token to the client, once
61
58
  * ```
62
59
  *
63
60
  * @throws {InvalidInputError} If `ttl` is empty or `userCommunicationMethodId` is not a positive integer.
@@ -69,7 +66,8 @@ export async function createSession(db, input) {
69
66
  if (typeof input.ttl !== 'string' || input.ttl.length === 0) {
70
67
  throw new InvalidInputError('ttl must be a non-empty Postgres interval string (e.g. "30 days")');
71
68
  }
72
- const sessionId = randomUUID();
69
+ const token = generateToken();
70
+ const sessionId = hashToken(token);
73
71
  const geo = input.geo ?? {};
74
72
  const { rows } = await db.query(INSERT_SESSION, [
75
73
  sessionId,
@@ -98,7 +96,7 @@ export async function createSession(db, input) {
98
96
  throw new Error('createSession: user_communication_method_id has no matching user');
99
97
  }
100
98
  return {
101
- sessionId: row.sessionId,
99
+ token,
102
100
  userId: userRow.userId,
103
101
  createdAt: row.createdAt,
104
102
  expiresAt: row.expiresAt,
@@ -1 +1 @@
1
- {"version":3,"file":"create-session.js","sourceRoot":"","sources":["../src/create-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AAChF,MAAM,WAAW,GAAG,UAAU,SAAS,EAAE,CAAC;AAE1C,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;;;;;;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24,14 +24,29 @@ export declare class SessionExpiredError extends AuthError {
24
24
  constructor(expiresAt: Date, message?: string);
25
25
  }
26
26
  /**
27
- * Thrown when a user does not have the role requested for a session.
27
+ * Thrown when a request asks to activate a role the user does not hold.
28
+ *
29
+ * Role selection and validation happen in `withSession` (TS): the pure
30
+ * `resolve_session` resolver returns the roles the user holds, and
31
+ * `withSession` rejects a requested role that isn't among them.
28
32
  */
29
- export declare class RoleNotAssignedError extends AuthError {
30
- readonly name = "RoleNotAssignedError";
31
- readonly code: "ROLE_NOT_ASSIGNED";
33
+ export declare class RoleNotHeldError extends AuthError {
34
+ readonly name = "RoleNotHeldError";
35
+ readonly code: "ROLE_NOT_HELD";
32
36
  readonly roleName: string;
33
37
  constructor(roleName: string, message?: string);
34
38
  }
39
+ /**
40
+ * Thrown when `withServiceContext` can't find a `users` row of
41
+ * `kind = 'service'` with the given name. Almost always a missing seed:
42
+ * the service principal must be provisioned before background writes run.
43
+ */
44
+ export declare class ServicePrincipalNotFoundError extends AuthError {
45
+ readonly name = "ServicePrincipalNotFoundError";
46
+ readonly code: "SERVICE_PRINCIPAL_NOT_FOUND";
47
+ readonly serviceName: string;
48
+ constructor(serviceName: string, message?: string);
49
+ }
35
50
  /**
36
51
  * Thrown when a function input fails validation (empty string, wrong type,
37
52
  * etc.) before the library will hit the database.
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC,SAAkB,IAAI,EAAE,MAAM,CAAe;IAC7C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAgB;CACtC;AAED;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;IACjD,SAAkB,IAAI,0BAA0B;IAChD,SAAkB,IAAI,EAAG,mBAAmB,CAAU;gBAE1C,OAAO,GAAE,MAA4B;CAGlD;AAED;;GAEG;AACH,qBAAa,mBAAoB,SAAQ,SAAS;I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;IAClD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;CAI/C;AAED;;;;GAIG;AACH,qBAAa,6BAA8B,SAAQ,SAAS;IAC1D,SAAkB,IAAI,mCAAmC;IACzD,SAAkB,IAAI,EAAG,6BAA6B,CAAU;IAChE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;gBAEjB,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;CAIlD;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,SAAS;IAC9C,SAAkB,IAAI,uBAAuB;IAC7C,SAAkB,IAAI,EAAG,eAAe,CAAU;gBAEtC,OAAO,EAAE,MAAM;CAG5B"}
package/dist/errors.js CHANGED
@@ -29,17 +29,35 @@ export class SessionExpiredError extends AuthError {
29
29
  }
30
30
  }
31
31
  /**
32
- * Thrown when a user does not have the role requested for a session.
32
+ * Thrown when a request asks to activate a role the user does not hold.
33
+ *
34
+ * Role selection and validation happen in `withSession` (TS): the pure
35
+ * `resolve_session` resolver returns the roles the user holds, and
36
+ * `withSession` rejects a requested role that isn't among them.
33
37
  */
34
- export class RoleNotAssignedError extends AuthError {
35
- name = 'RoleNotAssignedError';
36
- code = 'ROLE_NOT_ASSIGNED';
38
+ export class RoleNotHeldError extends AuthError {
39
+ name = 'RoleNotHeldError';
40
+ code = 'ROLE_NOT_HELD';
37
41
  roleName;
38
42
  constructor(roleName, message) {
39
- super(message ?? `User does not have role: ${roleName}`);
43
+ super(message ?? `User does not hold role: ${roleName}`);
40
44
  this.roleName = roleName;
41
45
  }
42
46
  }
47
+ /**
48
+ * Thrown when `withServiceContext` can't find a `users` row of
49
+ * `kind = 'service'` with the given name. Almost always a missing seed:
50
+ * the service principal must be provisioned before background writes run.
51
+ */
52
+ export class ServicePrincipalNotFoundError extends AuthError {
53
+ name = 'ServicePrincipalNotFoundError';
54
+ code = 'SERVICE_PRINCIPAL_NOT_FOUND';
55
+ serviceName;
56
+ constructor(serviceName, message) {
57
+ super(message ?? `No service principal named: ${serviceName}`);
58
+ this.serviceName = serviceName;
59
+ }
60
+ }
43
61
  /**
44
62
  * Thrown when a function input fails validation (empty string, wrong type,
45
63
  * etc.) before the library will hit the database.
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAChB,IAAI,GAAW,WAAW,CAAC;IACpC,IAAI,GAAW,YAAY,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,OAAO,oBAAqB,SAAQ,SAAS;IAC/B,IAAI,GAAG,sBAAsB,CAAC;IAC9B,IAAI,GAAG,mBAA4B,CAAC;IAEtD,YAAY,UAAkB,mBAAmB;QAC/C,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,SAAS;IAC9B,IAAI,GAAG,qBAAqB,CAAC;IAC7B,IAAI,GAAG,iBAA0B,CAAC;IAC3C,SAAS,CAAO;IAEzB,YAAY,SAAe,EAAE,OAAgB;QAC3C,KAAK,CAAC,OAAO,IAAI,sBAAsB,SAAS,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QAClE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,oBAAqB,SAAQ,SAAS;IAC/B,IAAI,GAAG,sBAAsB,CAAC;IAC9B,IAAI,GAAG,mBAA4B,CAAC;IAC7C,QAAQ,CAAS;IAE1B,YAAY,QAAgB,EAAE,OAAgB;QAC5C,KAAK,CAAC,OAAO,IAAI,4BAA4B,QAAQ,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,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IAAI,GAAG,6BAAsC,CAAC;IACvD,WAAW,CAAS;IAE7B,YAAY,WAAmB,EAAE,OAAgB;QAC/C,KAAK,CAAC,OAAO,IAAI,+BAA+B,WAAW,EAAE,CAAC,CAAC;QAC/D,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,SAAS;IAC5B,IAAI,GAAG,mBAAmB,CAAC;IAC3B,IAAI,GAAG,eAAwB,CAAC;IAElD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"find-user-by-communication-method.d.ts","sourceRoot":"","sources":["../src/find-user-by-communication-method.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AActF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,6BAA6B,CACjD,EAAE,EAAE,SAAS,EACb,KAAK,EAAE,aAAa,GACnB,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAa3C"}
1
+ {"version":3,"file":"find-user-by-communication-method.d.ts","sourceRoot":"","sources":["../src/find-user-by-communication-method.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAkBtF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,6BAA6B,CACjD,EAAE,EAAE,SAAS,EACb,KAAK,EAAE,aAAa,GACnB,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAa3C"}
@@ -6,8 +6,12 @@ const SELECT_BY_COMMUNICATION_METHOD = `
6
6
  FROM user_communication_methods ucm
7
7
  JOIN communication_channels cc
8
8
  ON cc.communication_channel_id = ucm.communication_channel_id
9
+ JOIN users u ON u.user_id = ucm.user_id
9
10
  WHERE cc.name = $1
10
11
  AND ucm.code = $2
12
+ AND ucm.deleted_at IS NULL
13
+ AND cc.deleted_at IS NULL
14
+ AND u.deleted_at IS NULL
11
15
  LIMIT 1
12
16
  `;
13
17
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"find-user-by-communication-method.js","sourceRoot":"","sources":["../src/find-user-by-communication-method.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,8BAA8B,GAAG;;;;;;;;;;CAUtC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,EAAa,EACb,KAAoB;IAEpB,IAAI,OAAO,KAAK,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACrE,MAAM,IAAI,iBAAiB,CAAC,0CAA0C,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,OAAO,KAAK,EAAE,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAA4B,8BAA8B,EAAE;QACzF,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,IAAI;KACX,CAAC,CAAC;IACH,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AACzB,CAAC"}
1
+ {"version":3,"file":"find-user-by-communication-method.js","sourceRoot":"","sources":["../src/find-user-by-communication-method.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,8BAA8B,GAAG;;;;;;;;;;;;;;CActC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,EAAa,EACb,KAAoB;IAEpB,IAAI,OAAO,KAAK,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACrE,MAAM,IAAI,iBAAiB,CAAC,0CAA0C,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,OAAO,KAAK,EAAE,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAA4B,8BAA8B,EAAE;QACzF,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,IAAI;KACX,CAAC,CAAC;IACH,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AACzB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"get-user-role-names.d.ts","sourceRoot":"","sources":["../src/get-user-role-names.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAc5C;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAOvF"}
1
+ {"version":3,"file":"get-user-role-names.d.ts","sourceRoot":"","sources":["../src/get-user-role-names.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAgB5C;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAOvF"}
@@ -4,6 +4,8 @@ const SELECT_ROLE_NAMES = `
4
4
  FROM user_roles ur
5
5
  JOIN roles r ON r.role_id = ur.role_id
6
6
  WHERE ur.user_id = $1
7
+ AND ur.deleted_at IS NULL
8
+ AND r.deleted_at IS NULL
7
9
  ORDER BY r.name
8
10
  `;
9
11
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"get-user-role-names.js","sourceRoot":"","sources":["../src/get-user-role-names.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,iBAAiB,GAAG;;;;;;CAMzB,CAAC;AAMF;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,EAAa,EAAE,MAAc;IAClE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,iBAAiB,CAAC,mCAAmC,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAc,iBAAiB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAC1E,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC"}
1
+ {"version":3,"file":"get-user-role-names.js","sourceRoot":"","sources":["../src/get-user-role-names.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,iBAAiB,GAAG;;;;;;;;CAQzB,CAAC;AAMF;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,EAAa,EAAE,MAAc;IAClE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,iBAAiB,CAAC,mCAAmC,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAc,iBAAiB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAC1E,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,13 +1,17 @@
1
- export { AuthError, SessionNotFoundError, SessionExpiredError, RoleNotAssignedError, InvalidInputError, } from './errors.js';
2
- export type { Queryable, Session, SessionContext, SessionAuth, CreateSessionInput, GeoLocation, UserByCommunicationMethod, FindUserQuery, Logger, WithSessionOptions, } from './types.js';
1
+ export { AuthError, SessionNotFoundError, SessionExpiredError, RoleNotHeldError, ServicePrincipalNotFoundError, InvalidInputError, } from './errors.js';
2
+ export type { Queryable, Session, SessionInfo, SessionContext, SessionIdentity, ScopeHook, SessionAuth, CreateSessionInput, GeoLocation, UserByCommunicationMethod, FindUserQuery, Logger, WithSessionOptions, } from './types.js';
3
3
  export { createSession } from './create-session.js';
4
4
  export { validateSession } from './validate-session.js';
5
- export { revokeSession } from './revoke-session.js';
5
+ export { revokeSession, revokeUserSessions, revokeTenantSessions } from './revoke-session.js';
6
+ export { touchSession } from './touch-session.js';
6
7
  export { findUserByCommunicationMethod } from './find-user-by-communication-method.js';
7
8
  export { getUserRoleNames } from './get-user-role-names.js';
8
9
  export { withSession } from './with-session.js';
9
- export { withTransaction } from './with-transaction.js';
10
- export { setSessionId, setRoleName, setTenantIds, setAllTenants, setSessionContext, SESSION_VAR_NAMES, } from './set-helpers.js';
11
10
  export { withServiceContext } from './with-service-context.js';
11
+ export { withTransaction } from '@smplcty/db';
12
+ export { IDENTITY_GUC, setLocal, setActorId, setSessionId, setActiveRole, setPrivileges, setIdentityContext, } from './set-helpers.js';
13
+ export { createMethodRouter } from './methods/router.js';
14
+ export { OtpNotAllowedError, VerificationFailedError } from './methods/errors.js';
15
+ export type { MethodHandler, MethodInitiateResult, MethodInitiateContext, MethodCompleteContext, ResolvedUser, MethodRouter, MethodRouterOptions, SignInOptions, AuthDomain, } from './methods/types.js';
12
16
  export { verifyDevOtp, isDevOtpEnrolled, generateDevOtpSecret, getDevOtpEnrollmentUri } from './dev-otp.js';
13
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAGrB,YAAY,EACV,SAAS,EACT,OAAO,EACP,cAAc,EACd,WAAW,EACX,kBAAkB,EAClB,WAAW,EACX,yBAAyB,EACzB,aAAa,EACb,MAAM,EACN,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAEvF,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAG5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAG/D,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.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AAY,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -1,18 +1,24 @@
1
1
  // Errors
2
- export { AuthError, SessionNotFoundError, SessionExpiredError, RoleNotAssignedError, InvalidInputError, } from './errors.js';
2
+ export { AuthError, SessionNotFoundError, SessionExpiredError, RoleNotHeldError, ServicePrincipalNotFoundError, InvalidInputError, } from './errors.js';
3
3
  // Session lifecycle
4
4
  export { createSession } from './create-session.js';
5
5
  export { validateSession } from './validate-session.js';
6
- export { revokeSession } from './revoke-session.js';
6
+ export { revokeSession, revokeUserSessions, revokeTenantSessions } from './revoke-session.js';
7
+ export { touchSession } from './touch-session.js';
7
8
  export { findUserByCommunicationMethod } from './find-user-by-communication-method.js';
8
9
  export { getUserRoleNames } from './get-user-role-names.js';
9
10
  // Request bootstrapping
10
11
  export { withSession } from './with-session.js';
11
- export { withTransaction } from './with-transaction.js';
12
- // Low-level helpers — must be called inside an open transaction.
13
- export { setSessionId, setRoleName, setTenantIds, setAllTenants, setSessionContext, SESSION_VAR_NAMES, } from './set-helpers.js';
14
- // Background service context — for Lambdas with no user session.
12
+ // Background service context — for workers/Lambdas with no user session.
15
13
  export { withServiceContext } from './with-service-context.js';
14
+ // The transaction primitive now lives in @smplcty/db; re-exported for
15
+ // convenience so consumers don't need a direct import for the common case.
16
+ export { withTransaction } from '@smplcty/db';
17
+ // Identity GUC helpers — must be called inside an open transaction.
18
+ export { IDENTITY_GUC, setLocal, setActorId, setSessionId, setActiveRole, setPrivileges, setIdentityContext, } from './set-helpers.js';
19
+ // Authentication methods — pluggable two-phase handlers + auth_domains router.
20
+ export { createMethodRouter } from './methods/router.js';
21
+ export { OtpNotAllowedError, VerificationFailedError } from './methods/errors.js';
16
22
  // Developer OTP — for devs whose phones can't receive Twilio SMS.
17
23
  export { verifyDevOtp, isDevOtpEnrolled, generateDevOtpSecret, getDevOtpEnrollmentUri } from './dev-otp.js';
18
24
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,SAAS;AACT,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAgBrB,oBAAoB;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AAEvF,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE5D,wBAAwB;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,iEAAiE;AACjE,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,iEAAiE;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,kEAAkE;AAClE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,SAAS;AACT,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,6BAA6B,EAC7B,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAmBrB,oBAAoB;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wCAAwC,CAAC;AACvF,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE5D,wBAAwB;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,yEAAyE;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,sEAAsE;AACtE,2EAA2E;AAC3E,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,oEAAoE;AACpE,OAAO,EACL,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,aAAa,EACb,aAAa,EACb,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAE1B,+EAA+E;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAalF,kEAAkE;AAClE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Generate a fresh opaque session token: 32 random bytes (256 bits of
3
+ * entropy), base64url-encoded so it's URL/cookie-safe. This is the raw
4
+ * bearer credential returned to the client — it is never stored.
5
+ */
6
+ export declare function generateToken(): string;
7
+ /**
8
+ * Derive the at-rest identifier for a token: its full SHA-256 hex digest.
9
+ * This is what's stored as `sessions.session_id`. A database leak exposes
10
+ * only hashes, which can't be replayed as bearer tokens.
11
+ *
12
+ * Distinct from `hashId` (a truncated, log-safe fingerprint): this is the
13
+ * full-width, collision-resistant key used for lookups.
14
+ */
15
+ export declare function hashToken(token: string): string;
16
+ //# sourceMappingURL=hash-token.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash-token.d.ts","sourceRoot":"","sources":["../../src/internal/hash-token.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAEtC;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE/C"}
@@ -0,0 +1,21 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ /**
3
+ * Generate a fresh opaque session token: 32 random bytes (256 bits of
4
+ * entropy), base64url-encoded so it's URL/cookie-safe. This is the raw
5
+ * bearer credential returned to the client — it is never stored.
6
+ */
7
+ export function generateToken() {
8
+ return randomBytes(32).toString('base64url');
9
+ }
10
+ /**
11
+ * Derive the at-rest identifier for a token: its full SHA-256 hex digest.
12
+ * This is what's stored as `sessions.session_id`. A database leak exposes
13
+ * only hashes, which can't be replayed as bearer tokens.
14
+ *
15
+ * Distinct from `hashId` (a truncated, log-safe fingerprint): this is the
16
+ * full-width, collision-resistant key used for lookups.
17
+ */
18
+ export function hashToken(token) {
19
+ return createHash('sha256').update(token).digest('hex');
20
+ }
21
+ //# sourceMappingURL=hash-token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash-token.js","sourceRoot":"","sources":["../../src/internal/hash-token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAEtD;;;;GAIG;AACH,MAAM,UAAU,aAAa;IAC3B,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAC/C,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,SAAS,CAAC,KAAa;IACrC,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC"}
@@ -0,0 +1,23 @@
1
+ import { AuthError } from '../errors.js';
2
+ /**
3
+ * Thrown when OTP (user-bound) sign-in is attempted for a tenant whose
4
+ * `allow_otp` is false — an SSO-only tenant. Enforced in the router so a
5
+ * crafted request can't bypass a hidden UI button.
6
+ */
7
+ export declare class OtpNotAllowedError extends AuthError {
8
+ readonly name = "OtpNotAllowedError";
9
+ readonly code: "OTP_NOT_ALLOWED";
10
+ readonly tenantId: number;
11
+ constructor(tenantId: number, message?: string);
12
+ }
13
+ /**
14
+ * Thrown by a handler's `complete` when the submitted credential fails
15
+ * verification (wrong/expired OTP, invalid id_token, unverifiable claims),
16
+ * or when a verified identity has no user and no provisioning is allowed.
17
+ */
18
+ export declare class VerificationFailedError extends AuthError {
19
+ readonly name = "VerificationFailedError";
20
+ readonly code: "VERIFICATION_FAILED";
21
+ constructor(message?: string);
22
+ }
23
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/methods/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;GAIG;AACH,qBAAa,kBAAmB,SAAQ,SAAS;IAC/C,SAAkB,IAAI,wBAAwB;IAC9C,SAAkB,IAAI,EAAG,iBAAiB,CAAU;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;CAI/C;AAED;;;;GAIG;AACH,qBAAa,uBAAwB,SAAQ,SAAS;IACpD,SAAkB,IAAI,6BAA6B;IACnD,SAAkB,IAAI,EAAG,qBAAqB,CAAU;gBAE5C,OAAO,GAAE,MAA8B;CAGpD"}
@@ -0,0 +1,28 @@
1
+ import { AuthError } from '../errors.js';
2
+ /**
3
+ * Thrown when OTP (user-bound) sign-in is attempted for a tenant whose
4
+ * `allow_otp` is false — an SSO-only tenant. Enforced in the router so a
5
+ * crafted request can't bypass a hidden UI button.
6
+ */
7
+ export class OtpNotAllowedError extends AuthError {
8
+ name = 'OtpNotAllowedError';
9
+ code = 'OTP_NOT_ALLOWED';
10
+ tenantId;
11
+ constructor(tenantId, message) {
12
+ super(message ?? `OTP sign-in is not allowed for tenant ${tenantId}`);
13
+ this.tenantId = tenantId;
14
+ }
15
+ }
16
+ /**
17
+ * Thrown by a handler's `complete` when the submitted credential fails
18
+ * verification (wrong/expired OTP, invalid id_token, unverifiable claims),
19
+ * or when a verified identity has no user and no provisioning is allowed.
20
+ */
21
+ export class VerificationFailedError extends AuthError {
22
+ name = 'VerificationFailedError';
23
+ code = 'VERIFICATION_FAILED';
24
+ constructor(message = 'Verification failed') {
25
+ super(message);
26
+ }
27
+ }
28
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/methods/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;GAIG;AACH,MAAM,OAAO,kBAAmB,SAAQ,SAAS;IAC7B,IAAI,GAAG,oBAAoB,CAAC;IAC5B,IAAI,GAAG,iBAA0B,CAAC;IAC3C,QAAQ,CAAS;IAE1B,YAAY,QAAgB,EAAE,OAAgB;QAC5C,KAAK,CAAC,OAAO,IAAI,yCAAyC,QAAQ,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,uBAAwB,SAAQ,SAAS;IAClC,IAAI,GAAG,yBAAyB,CAAC;IACjC,IAAI,GAAG,qBAA8B,CAAC;IAExD,YAAY,UAAkB,qBAAqB;QACjD,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF"}
@@ -0,0 +1,92 @@
1
+ import * as oauth from 'oauth4webapi';
2
+ import type { Queryable } from '../../types.js';
3
+ import type { AuthDomain, ResolvedUser } from '../types.js';
4
+ /**
5
+ * The OIDC provider config read from `auth_domains.integration_params`.
6
+ * Public values only — the `client_secret` is supplied out-of-band via
7
+ * {@link OidcHandlerOptions.clientSecret} (from the app's secret store), never
8
+ * stored here.
9
+ */
10
+ export interface OidcParams {
11
+ /** Provider issuer URL (discovery is fetched from `${issuer}/.well-known/openid-configuration`). */
12
+ issuer: string;
13
+ /** This app's OIDC client id. */
14
+ clientId: string;
15
+ /** Where the provider sends the user back (must match the app's callback route). */
16
+ redirectUri: string;
17
+ /** OAuth scope. Defaults to `openid email profile`. */
18
+ scope?: string;
19
+ }
20
+ /**
21
+ * The transient login state produced by {@link OidcHandler.initiate} that the
22
+ * **app must persist** across the redirect (a short-lived signed cookie keyed
23
+ * by `state`) and hand back to {@link OidcHandler.complete}. The library holds
24
+ * no pre-auth state of its own.
25
+ */
26
+ export interface OidcLoginState {
27
+ state: string;
28
+ nonce: string;
29
+ codeVerifier: string;
30
+ }
31
+ export interface OidcAuthorization {
32
+ /** Where to redirect the browser to begin the OIDC flow. */
33
+ redirectUrl: string;
34
+ /** Persist this (signed cookie) and pass it to `complete` on callback. */
35
+ loginState: OidcLoginState;
36
+ }
37
+ export interface OidcHandlerOptions {
38
+ /**
39
+ * Resolve the confidential client secret for an `auth_domains` row, from the
40
+ * app's secret store (Vercel/SSM) — NOT from the database. Return `undefined`
41
+ * for a public (PKCE-only) client.
42
+ */
43
+ clientSecret?: (authDomain: AuthDomain<OidcParams>) => string | undefined | Promise<string | undefined>;
44
+ /**
45
+ * Provision a user when a verified identity has no existing communication
46
+ * method. The app owns the writes + audit attribution (it knows the tenant
47
+ * from `authDomain.tenantId`). Omit to reject unprovisioned identities.
48
+ */
49
+ provisionUser?: (input: {
50
+ db: Queryable;
51
+ authDomain: AuthDomain<OidcParams>;
52
+ claims: ValidatedClaims;
53
+ }) => Promise<ResolvedUser>;
54
+ /** Override `fetch` (tests inject a mock for discovery + token endpoints). */
55
+ fetch?: typeof globalThis.fetch;
56
+ }
57
+ type ValidatedClaims = NonNullable<ReturnType<typeof oauth.getValidatedIdTokenClaims>>;
58
+ /**
59
+ * The org-bound OIDC handler (opt-in subpath `@smplcty/auth/oidc`), built on
60
+ * **`oauth4webapi`** (ADR-0001). Two phases:
61
+ *
62
+ * - `initiate(authDomain)` — discovery + PKCE/state/nonce → an authorization
63
+ * redirect URL and the `loginState` to persist.
64
+ * - `complete({ callbackUrl, loginState })` — validate the callback, exchange
65
+ * the code, verify the `id_token` (signature, claims, nonce) → resolve (or
66
+ * provision) the user.
67
+ *
68
+ * `oauth4webapi` is an **optional peer**; install it to use this subpath.
69
+ *
70
+ * ```ts
71
+ * const oidc = oidcHandler({ clientSecret: (ad) => secrets.get(ad.tenantId) });
72
+ * const { redirectUrl, loginState } = await oidc.initiate(authDomain);
73
+ * // ...store loginState in a signed cookie keyed by loginState.state, redirect...
74
+ * const user = await oidc.complete({ db: pool, authDomain, callbackUrl, loginState });
75
+ * const session = await createSession(pool, { userCommunicationMethodId: user.userCommunicationMethodId, ttl: '30 days' });
76
+ * ```
77
+ */
78
+ export interface OidcHandler {
79
+ initiate(authDomain: AuthDomain<OidcParams>, opts?: {
80
+ loginHint?: string;
81
+ }): Promise<OidcAuthorization>;
82
+ complete(input: {
83
+ db: Queryable;
84
+ authDomain: AuthDomain<OidcParams>;
85
+ /** The full callback URL (including the query string from the provider). */
86
+ callbackUrl: string | URL;
87
+ loginState: OidcLoginState;
88
+ }): Promise<ResolvedUser>;
89
+ }
90
+ export declare function oidcHandler(options?: OidcHandlerOptions): OidcHandler;
91
+ export {};
92
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/methods/oidc/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAGtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE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AAC,iBAAiB,CAAC,CAAC;IACxG,QAAQ,CAAC,KAAK,EAAE;QACd,EAAE,EAAE,SAAS,CAAC;QACd,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;QACnC,4EAA4E;QAC5E,WAAW,EAAE,MAAM,GAAG,GAAG,CAAC;QAC1B,UAAU,EAAE,cAAc,CAAC;KAC5B,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;CAC3B;AA+BD,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAsFzE"}
@@ -0,0 +1,104 @@
1
+ import * as oauth from 'oauth4webapi';
2
+ import { InvalidInputError } from '../../errors.js';
3
+ import { findUserByCommunicationMethod } from '../../find-user-by-communication-method.js';
4
+ import { VerificationFailedError } from '../errors.js';
5
+ function paramsOf(authDomain) {
6
+ if (authDomain.integrationType !== 'oidc') {
7
+ throw new InvalidInputError(`OidcHandler requires integration_type 'oidc', got '${authDomain.integrationType}'`);
8
+ }
9
+ const p = authDomain.integrationParams;
10
+ if (!p.issuer || !p.clientId || !p.redirectUri) {
11
+ throw new InvalidInputError('OIDC integration_params must include issuer, clientId, and redirectUri');
12
+ }
13
+ return p;
14
+ }
15
+ // Discovery is cached per issuer for the process lifetime (warm-start friendly).
16
+ // Failures are not cached.
17
+ const discoveryCache = new Map();
18
+ function authorizationServer(issuer, fetchImpl) {
19
+ let cached = discoveryCache.get(issuer);
20
+ if (!cached) {
21
+ const issuerUrl = new URL(issuer);
22
+ const options = fetchImpl ? { [oauth.customFetch]: fetchImpl } : undefined;
23
+ cached = oauth
24
+ .discoveryRequest(issuerUrl, options)
25
+ .then((response) => oauth.processDiscoveryResponse(issuerUrl, response));
26
+ cached.catch(() => discoveryCache.delete(issuer));
27
+ discoveryCache.set(issuer, cached);
28
+ }
29
+ return cached;
30
+ }
31
+ export function oidcHandler(options = {}) {
32
+ return {
33
+ async initiate(authDomain, opts = {}) {
34
+ const params = paramsOf(authDomain);
35
+ const as = await authorizationServer(params.issuer, options.fetch);
36
+ if (!as.authorization_endpoint) {
37
+ throw new InvalidInputError(`OIDC issuer ${params.issuer} exposes no authorization_endpoint`);
38
+ }
39
+ const codeVerifier = oauth.generateRandomCodeVerifier();
40
+ const codeChallenge = await oauth.calculatePKCECodeChallenge(codeVerifier);
41
+ const state = oauth.generateRandomState();
42
+ const nonce = oauth.generateRandomNonce();
43
+ const url = new URL(as.authorization_endpoint);
44
+ url.searchParams.set('client_id', params.clientId);
45
+ url.searchParams.set('redirect_uri', params.redirectUri);
46
+ url.searchParams.set('response_type', 'code');
47
+ url.searchParams.set('scope', params.scope ?? 'openid email profile');
48
+ url.searchParams.set('code_challenge', codeChallenge);
49
+ url.searchParams.set('code_challenge_method', 'S256');
50
+ url.searchParams.set('state', state);
51
+ url.searchParams.set('nonce', nonce);
52
+ if (opts.loginHint) {
53
+ url.searchParams.set('login_hint', opts.loginHint);
54
+ }
55
+ return { redirectUrl: url.toString(), loginState: { state, nonce, codeVerifier } };
56
+ },
57
+ async complete({ db, authDomain, callbackUrl, loginState }) {
58
+ const params = paramsOf(authDomain);
59
+ const as = await authorizationServer(params.issuer, options.fetch);
60
+ const client = { client_id: params.clientId };
61
+ const secret = options.clientSecret ? await options.clientSecret(authDomain) : undefined;
62
+ const clientAuth = secret ? oauth.ClientSecretPost(secret) : oauth.None();
63
+ const currentUrl = typeof callbackUrl === 'string' ? new URL(callbackUrl) : callbackUrl;
64
+ const fetchOption = options.fetch ? { [oauth.customFetch]: options.fetch } : undefined;
65
+ let claims;
66
+ try {
67
+ const callbackParams = oauth.validateAuthResponse(as, client, currentUrl, loginState.state);
68
+ const response = await oauth.authorizationCodeGrantRequest(as, client, clientAuth, callbackParams, params.redirectUri, loginState.codeVerifier, fetchOption);
69
+ const tokenResponse = await oauth.processAuthorizationCodeResponse(as, client, response, {
70
+ expectedNonce: loginState.nonce,
71
+ requireIdToken: true,
72
+ });
73
+ const validated = oauth.getValidatedIdTokenClaims(tokenResponse);
74
+ if (!validated) {
75
+ throw new VerificationFailedError('OIDC token response carried no id_token');
76
+ }
77
+ claims = validated;
78
+ }
79
+ catch (err) {
80
+ if (err instanceof VerificationFailedError)
81
+ throw err;
82
+ throw new VerificationFailedError('OIDC authorization failed');
83
+ }
84
+ // Entra often carries the address in preferred_username rather than email.
85
+ const email = typeof claims.email === 'string'
86
+ ? claims.email
87
+ : typeof claims.preferred_username === 'string'
88
+ ? claims.preferred_username
89
+ : undefined;
90
+ if (!email) {
91
+ throw new VerificationFailedError('OIDC id_token has no email or preferred_username');
92
+ }
93
+ const existing = await findUserByCommunicationMethod(db, { channel: 'email', code: email });
94
+ if (existing) {
95
+ return existing;
96
+ }
97
+ if (options.provisionUser) {
98
+ return options.provisionUser({ db, authDomain, claims });
99
+ }
100
+ throw new VerificationFailedError('No user for verified identity and provisioning is disabled');
101
+ },
102
+ };
103
+ }
104
+ //# sourceMappingURL=index.js.map