@smplcty/auth 0.6.4 → 1.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 +186 -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 +37 -0
  25. package/dist/methods/errors.d.ts.map +1 -0
  26. package/dist/methods/errors.js +48 -0
  27. package/dist/methods/errors.js.map +1 -0
  28. package/dist/methods/oidc/index.d.ts +65 -0
  29. package/dist/methods/oidc/index.d.ts.map +1 -0
  30. package/dist/methods/oidc/index.js +76 -0
  31. package/dist/methods/oidc/index.js.map +1 -0
  32. package/dist/methods/router.d.ts +39 -0
  33. package/dist/methods/router.d.ts.map +1 -0
  34. package/dist/methods/router.js +153 -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 +124 -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 +32 -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
@@ -0,0 +1,39 @@
1
+ import type { MethodRouter, MethodRouterOptions } from './types.js';
2
+ /**
3
+ * Build a tenant-centric method router over a set of injected handlers.
4
+ *
5
+ * Sign-in discovery is by **sub-domain → tenant** (the app parses the request
6
+ * Host to a slug). The router lists that tenant's `auth_domains` and dispatches
7
+ * the chosen one (by `auth_domain_id`) to the handler registered for its
8
+ * `integration_type`. The user-bound OTP path is separate and **gated by the
9
+ * tenant's `allow_otp`** — enforced here, not just in the UI.
10
+ *
11
+ * Auth core stays protocol-free: handlers are injected. Install
12
+ * `@smplcty/auth/oidc` / `@smplcty/auth/twilio` (each with its protocol peer)
13
+ * and pass them in.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const router = createMethodRouter({
18
+ * db: pool,
19
+ * handlers: { oidc: oidcHandler() },
20
+ * otpHandler: twilioVerifyHandler({ client }),
21
+ * });
22
+ *
23
+ * // sign-in page (app already parsed Host → 'acme'):
24
+ * const opts = await router.signInOptions({ tenantSlug: 'acme' });
25
+ * // opts = { tenantId, authDomains: [...], otpAllowed }
26
+ * // 0 IdPs → OTP form; 1 → redirect to initiate(); N → a button per IdP
27
+ *
28
+ * // OIDC: user clicked the "Microsoft" button (authDomainId 1)
29
+ * const { redirectUrl } = await router.initiate(1);
30
+ * // ...callback: app loaded the auth_domain it stored against `state`
31
+ * const user = await router.complete(1, idToken);
32
+ *
33
+ * // OTP (only when opts.otpAllowed):
34
+ * await router.initiateOtp({ tenantId: opts.tenantId, identifier: phone });
35
+ * const user2 = await router.completeOtp({ tenantId: opts.tenantId, identifier: phone, credential: code });
36
+ * ```
37
+ */
38
+ export declare function createMethodRouter(options: MethodRouterOptions): MethodRouter;
39
+ //# sourceMappingURL=router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/methods/router.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAc,YAAY,EAAE,mBAAmB,EAA+B,MAAM,YAAY,CAAC;AA2C7G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,YAAY,CAyF7E"}
@@ -0,0 +1,153 @@
1
+ import { InvalidInputError } from '../errors.js';
2
+ import { OtpNotAllowedError, UnknownMethodError } from './errors.js';
3
+ const SELECT_TENANT_BY_SLUG = `
4
+ SELECT tenant_id AS "tenantId", allow_otp AS "allowOtp"
5
+ FROM tenants
6
+ WHERE slug = $1 AND deleted_at IS NULL
7
+ LIMIT 1
8
+ `;
9
+ const SELECT_ALLOW_OTP = `
10
+ SELECT allow_otp AS "allowOtp"
11
+ FROM tenants
12
+ WHERE tenant_id = $1 AND deleted_at IS NULL
13
+ LIMIT 1
14
+ `;
15
+ const AUTH_DOMAIN_COLUMNS = `
16
+ auth_domain_id AS "authDomainId",
17
+ tenant_id AS "tenantId",
18
+ display_name AS "displayName",
19
+ integration_type AS "integrationType",
20
+ integration_params AS "integrationParams"
21
+ `;
22
+ const SELECT_AUTH_DOMAINS_BY_TENANT = `
23
+ SELECT ${AUTH_DOMAIN_COLUMNS}
24
+ FROM auth_domains
25
+ WHERE tenant_id = $1 AND deleted_at IS NULL
26
+ ORDER BY display_name
27
+ `;
28
+ const SELECT_AUTH_DOMAIN_BY_ID = `
29
+ SELECT ${AUTH_DOMAIN_COLUMNS}
30
+ FROM auth_domains
31
+ WHERE auth_domain_id = $1 AND deleted_at IS NULL
32
+ LIMIT 1
33
+ `;
34
+ /**
35
+ * Build a tenant-centric method router over a set of injected handlers.
36
+ *
37
+ * Sign-in discovery is by **sub-domain → tenant** (the app parses the request
38
+ * Host to a slug). The router lists that tenant's `auth_domains` and dispatches
39
+ * the chosen one (by `auth_domain_id`) to the handler registered for its
40
+ * `integration_type`. The user-bound OTP path is separate and **gated by the
41
+ * tenant's `allow_otp`** — enforced here, not just in the UI.
42
+ *
43
+ * Auth core stays protocol-free: handlers are injected. Install
44
+ * `@smplcty/auth/oidc` / `@smplcty/auth/twilio` (each with its protocol peer)
45
+ * and pass them in.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const router = createMethodRouter({
50
+ * db: pool,
51
+ * handlers: { oidc: oidcHandler() },
52
+ * otpHandler: twilioVerifyHandler({ client }),
53
+ * });
54
+ *
55
+ * // sign-in page (app already parsed Host → 'acme'):
56
+ * const opts = await router.signInOptions({ tenantSlug: 'acme' });
57
+ * // opts = { tenantId, authDomains: [...], otpAllowed }
58
+ * // 0 IdPs → OTP form; 1 → redirect to initiate(); N → a button per IdP
59
+ *
60
+ * // OIDC: user clicked the "Microsoft" button (authDomainId 1)
61
+ * const { redirectUrl } = await router.initiate(1);
62
+ * // ...callback: app loaded the auth_domain it stored against `state`
63
+ * const user = await router.complete(1, idToken);
64
+ *
65
+ * // OTP (only when opts.otpAllowed):
66
+ * await router.initiateOtp({ tenantId: opts.tenantId, identifier: phone });
67
+ * const user2 = await router.completeOtp({ tenantId: opts.tenantId, identifier: phone, credential: code });
68
+ * ```
69
+ */
70
+ export function createMethodRouter(options) {
71
+ const { db, handlers, otpHandler } = options;
72
+ const q = db;
73
+ async function loadAuthDomain(authDomainId) {
74
+ if (!Number.isInteger(authDomainId) || authDomainId <= 0) {
75
+ throw new InvalidInputError('authDomainId must be a positive integer');
76
+ }
77
+ const { rows } = await q.query(SELECT_AUTH_DOMAIN_BY_ID, [authDomainId]);
78
+ const authDomain = rows[0];
79
+ if (!authDomain) {
80
+ throw new UnknownMethodError(String(authDomainId));
81
+ }
82
+ return authDomain;
83
+ }
84
+ async function assertOtpAllowed(tenantId) {
85
+ if (!Number.isInteger(tenantId) || tenantId <= 0) {
86
+ throw new InvalidInputError('tenantId must be a positive integer');
87
+ }
88
+ if (!otpHandler) {
89
+ throw new OtpNotAllowedError(tenantId, 'No OTP handler is configured');
90
+ }
91
+ const { rows } = await q.query(SELECT_ALLOW_OTP, [tenantId]);
92
+ const row = rows[0];
93
+ // Unknown tenant or allow_otp=false both deny — fail closed.
94
+ if (!row || row.allowOtp !== true) {
95
+ throw new OtpNotAllowedError(tenantId);
96
+ }
97
+ }
98
+ return {
99
+ async signInOptions({ tenantSlug }) {
100
+ if (typeof tenantSlug !== 'string' || tenantSlug.length === 0) {
101
+ throw new InvalidInputError('tenantSlug must be a non-empty string');
102
+ }
103
+ const { rows } = await q.query(SELECT_TENANT_BY_SLUG, [tenantSlug]);
104
+ const tenant = rows[0];
105
+ if (!tenant) {
106
+ return null;
107
+ }
108
+ const { rows: authDomains } = await q.query(SELECT_AUTH_DOMAINS_BY_TENANT, [tenant.tenantId]);
109
+ return {
110
+ tenantId: tenant.tenantId,
111
+ authDomains,
112
+ otpAllowed: tenant.allowOtp === true && !!otpHandler,
113
+ };
114
+ },
115
+ async initiate(authDomainId) {
116
+ const authDomain = await loadAuthDomain(authDomainId);
117
+ const handler = handlers[authDomain.integrationType];
118
+ if (!handler) {
119
+ throw new UnknownMethodError(String(authDomainId), authDomain.integrationType);
120
+ }
121
+ return handler.initiate({ db, authDomain });
122
+ },
123
+ async complete(authDomainId, credential) {
124
+ if (typeof credential !== 'string' || credential.length === 0) {
125
+ throw new InvalidInputError('credential must be a non-empty string');
126
+ }
127
+ const authDomain = await loadAuthDomain(authDomainId);
128
+ const handler = handlers[authDomain.integrationType];
129
+ if (!handler) {
130
+ throw new UnknownMethodError(String(authDomainId), authDomain.integrationType);
131
+ }
132
+ return handler.complete({ db, authDomain, credential });
133
+ },
134
+ async initiateOtp({ tenantId, identifier }) {
135
+ if (typeof identifier !== 'string' || identifier.length === 0) {
136
+ throw new InvalidInputError('identifier must be a non-empty string');
137
+ }
138
+ await assertOtpAllowed(tenantId);
139
+ return otpHandler.initiate({ db, authDomain: null, identifier });
140
+ },
141
+ async completeOtp({ tenantId, identifier, credential }) {
142
+ if (typeof identifier !== 'string' || identifier.length === 0) {
143
+ throw new InvalidInputError('identifier must be a non-empty string');
144
+ }
145
+ if (typeof credential !== 'string' || credential.length === 0) {
146
+ throw new InvalidInputError('credential must be a non-empty string');
147
+ }
148
+ await assertOtpAllowed(tenantId);
149
+ return otpHandler.complete({ db, authDomain: null, identifier, credential });
150
+ },
151
+ };
152
+ }
153
+ //# sourceMappingURL=router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.js","sourceRoot":"","sources":["../../src/methods/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGrE,MAAM,qBAAqB,GAAG;;;;;CAK7B,CAAC;AAEF,MAAM,gBAAgB,GAAG;;;;;CAKxB,CAAC;AAEF,MAAM,mBAAmB,GAAG;;;;;;CAM3B,CAAC;AAEF,MAAM,6BAA6B,GAAG;WAC3B,mBAAmB;;;;CAI7B,CAAC;AAEF,MAAM,wBAAwB,GAAG;WACtB,mBAAmB;;;;CAI7B,CAAC;AAOF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAA4B;IAC7D,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC;IAC7C,MAAM,CAAC,GAAG,EAAe,CAAC;IAE1B,KAAK,UAAU,cAAc,CAAC,YAAoB;QAChD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,YAAY,CAAC,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;YACzD,MAAM,IAAI,iBAAiB,CAAC,yCAAyC,CAAC,CAAC;QACzE,CAAC;QACD,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CA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AY,CAAC,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;YACjF,CAAC;YACD,OAAO,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;QAC1D,CAAC;QAED,KAAK,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE;YACxC,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;YACvE,CAAC;YACD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,CAAC;YACjC,OAAO,UAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,KAAK,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE;YACpD,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;YACvE,CAAC;YACD,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9D,MAAM,IAAI,iBAAiB,CAAC,uCAAuC,CAAC,CAAC;YACvE,CAAC;YACD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,CAAC;YACjC,OAAO,UAAW,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;QAChF,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { TwilioVerifyClient, VerificationChannel } from '@smplcty/twilio';
2
+ import type { MethodHandler } from '../types.js';
3
+ /**
4
+ * How an identifier maps onto a communication channel.
5
+ *
6
+ * - `channelName` — the `communication_channels.name` to match the user
7
+ * on (e.g. 'email' / 'phone').
8
+ * - `verifyChannel` — the Twilio Verify delivery channel ('sms' / 'email').
9
+ */
10
+ export interface ResolvedChannel {
11
+ channelName: string;
12
+ verifyChannel: VerificationChannel;
13
+ }
14
+ export interface TwilioVerifyHandlerOptions {
15
+ /** A Twilio Verify client from `createTwilioVerifyClient` (in the app). */
16
+ client: TwilioVerifyClient;
17
+ /** Map an identifier to its channel. Default: contains '@' → email,
18
+ * otherwise phone/sms. */
19
+ resolveChannel?: (identifier: string) => ResolvedChannel;
20
+ }
21
+ /**
22
+ * The user-bound Twilio Verify method handler (opt-in subpath
23
+ * `@smplcty/auth/twilio`). Phase 1 sends an OTP (skipping the send for
24
+ * dev-OTP-enrolled users); phase 2 verifies the submitted code — dev-OTP
25
+ * first, then Twilio — and resolves the existing user.
26
+ *
27
+ * User-bound: it never provisions. The user must already have a
28
+ * `user_communication_methods` row for the identifier. To avoid a
29
+ * user-enumeration oracle, `initiate` reports `otpSent` even for an unknown
30
+ * identifier (it just doesn't send); `complete` fails verification.
31
+ *
32
+ * Drives `@smplcty/twilio` (an **optional peer**); auth core depends on
33
+ * neither it nor `jose`. Install the peer and pass a client:
34
+ *
35
+ * ```ts
36
+ * import { createTwilioVerifyClient } from '@smplcty/twilio';
37
+ * import { twilioVerifyHandler } from '@smplcty/auth/twilio';
38
+ *
39
+ * const handler = twilioVerifyHandler({ client: createTwilioVerifyClient(cfg) });
40
+ * const router = createMethodRouter({ db: pool, handlers: {}, defaultHandler: handler });
41
+ * ```
42
+ */
43
+ export declare function twilioVerifyHandler(options: TwilioVerifyHandlerOptions): MethodHandler;
44
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/methods/twilio/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAK/E,OAAO,KAAK,EAEV,aAAa,EAId,MAAM,aAAa,CAAC;AAErB;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,mBAAmB,CAAC;CACpC;AAED,MAAM,WAAW,0BAA0B;IACzC,2EAA2E;IAC3E,MAAM,EAAE,kBAAkB,CAAC;IAC3B;+BAC2B;IAC3B,cAAc,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,eAAe,CAAC;CAC1D;AAiBD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,aAAa,CA2CtF"}
@@ -0,0 +1,77 @@
1
+ import { InvalidInputError } from '../../errors.js';
2
+ import { findUserByCommunicationMethod } from '../../find-user-by-communication-method.js';
3
+ import { verifyDevOtp, isDevOtpEnrolled } from '../../dev-otp.js';
4
+ import { VerificationFailedError } from '../errors.js';
5
+ function defaultResolveChannel(identifier) {
6
+ return identifier.includes('@')
7
+ ? { channelName: 'email', verifyChannel: 'email' }
8
+ : { channelName: 'phone', verifyChannel: 'sms' };
9
+ }
10
+ // User-bound: the identifier (phone/email) is required. The router always
11
+ // supplies it via initiateOtp/completeOtp; this guards direct handler use.
12
+ function requireIdentifier(identifier) {
13
+ if (typeof identifier !== 'string' || identifier.length === 0) {
14
+ throw new InvalidInputError('the Twilio handler requires a non-empty identifier');
15
+ }
16
+ return identifier;
17
+ }
18
+ /**
19
+ * The user-bound Twilio Verify method handler (opt-in subpath
20
+ * `@smplcty/auth/twilio`). Phase 1 sends an OTP (skipping the send for
21
+ * dev-OTP-enrolled users); phase 2 verifies the submitted code — dev-OTP
22
+ * first, then Twilio — and resolves the existing user.
23
+ *
24
+ * User-bound: it never provisions. The user must already have a
25
+ * `user_communication_methods` row for the identifier. To avoid a
26
+ * user-enumeration oracle, `initiate` reports `otpSent` even for an unknown
27
+ * identifier (it just doesn't send); `complete` fails verification.
28
+ *
29
+ * Drives `@smplcty/twilio` (an **optional peer**); auth core depends on
30
+ * neither it nor `jose`. Install the peer and pass a client:
31
+ *
32
+ * ```ts
33
+ * import { createTwilioVerifyClient } from '@smplcty/twilio';
34
+ * import { twilioVerifyHandler } from '@smplcty/auth/twilio';
35
+ *
36
+ * const handler = twilioVerifyHandler({ client: createTwilioVerifyClient(cfg) });
37
+ * const router = createMethodRouter({ db: pool, handlers: {}, defaultHandler: handler });
38
+ * ```
39
+ */
40
+ export function twilioVerifyHandler(options) {
41
+ const { client } = options;
42
+ const resolveChannel = options.resolveChannel ?? defaultResolveChannel;
43
+ return {
44
+ async initiate(ctx) {
45
+ const identifier = requireIdentifier(ctx.identifier);
46
+ const { channelName, verifyChannel } = resolveChannel(identifier);
47
+ const user = await findUserByCommunicationMethod(ctx.db, { channel: channelName, code: identifier });
48
+ // Unknown identifier: report sent without sending (anti-enumeration).
49
+ if (!user) {
50
+ return { otpSent: true };
51
+ }
52
+ // Dev-OTP-enrolled devs generate their code from an authenticator
53
+ // app, so skip the (likely undeliverable) SMS.
54
+ if (await isDevOtpEnrolled(ctx.db, user.userCommunicationMethodId)) {
55
+ return { otpSent: true };
56
+ }
57
+ await client.sendVerificationCode({ channel: verifyChannel, to: identifier });
58
+ return { otpSent: true };
59
+ },
60
+ async complete(ctx) {
61
+ const identifier = requireIdentifier(ctx.identifier);
62
+ const { channelName } = resolveChannel(identifier);
63
+ const user = await findUserByCommunicationMethod(ctx.db, { channel: channelName, code: identifier });
64
+ if (!user) {
65
+ throw new VerificationFailedError();
66
+ }
67
+ // Dev-OTP first (authenticator-app code), then Twilio Verify.
68
+ const okDev = await verifyDevOtp(ctx.db, user.userCommunicationMethodId, ctx.credential);
69
+ const ok = okDev || (await client.verifyVerificationCode({ to: identifier, code: ctx.credential }));
70
+ if (!ok) {
71
+ throw new VerificationFailedError();
72
+ }
73
+ return user;
74
+ },
75
+ };
76
+ }
77
+ //# sourceMappingURL=index.js.map
@@ -0,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CAAC,CAAC;YACpG,IAAI,CAAC,EAAE,EAAE,CAAC;gBACR,MAAM,IAAI,uBAAuB,EAAE,CAAC;YACtC,CAAC;YAED,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,124 @@
1
+ import type { Queryable } from '../types.js';
2
+ /**
3
+ * An `auth_domains` row — one of a tenant's org-bound sign-in IdPs. A tenant
4
+ * has 0..N of these; the router lists them for a tenant and dispatches by
5
+ * `integrationType`. Rows are configured at runtime and resolved by
6
+ * `authDomainId` (there is no stable text key); `displayName` is the button
7
+ * label when a tenant has more than one.
8
+ *
9
+ * @typeParam TParams - Shape of `integration_params`. Defaults to an open
10
+ * record; narrow it in a handler.
11
+ */
12
+ export interface AuthDomain<TParams = Record<string, unknown>> {
13
+ readonly authDomainId: number;
14
+ readonly tenantId: number;
15
+ /** Button label when the tenant has several IdPs (e.g. "Microsoft"). */
16
+ readonly displayName: string;
17
+ /** Selects the handler — e.g. 'oidc'. */
18
+ readonly integrationType: string;
19
+ /** Provider config + provisioning policy. Handler-specific. */
20
+ readonly integrationParams: TParams;
21
+ }
22
+ /**
23
+ * A user verified by a method handler, ready for `createSession`.
24
+ */
25
+ export interface ResolvedUser {
26
+ readonly userId: number;
27
+ readonly userCommunicationMethodId: number;
28
+ }
29
+ /**
30
+ * Result of a handler's `initiate` phase: either an OTP was sent
31
+ * (user-bound methods) or the caller should redirect (org-bound methods).
32
+ */
33
+ export type MethodInitiateResult = {
34
+ readonly otpSent: true;
35
+ } | {
36
+ readonly redirectUrl: string;
37
+ };
38
+ /**
39
+ * Context handed to a handler's `initiate`.
40
+ */
41
+ export interface MethodInitiateContext {
42
+ /** A connection or pool the handler may query (e.g. to find the user). */
43
+ readonly db: Queryable;
44
+ /** The matched `auth_domains` row for an org-bound method, or null for the
45
+ * user-bound (OTP) handler. */
46
+ readonly authDomain: AuthDomain | null;
47
+ /** The identifier the user entered (email/phone). Required by user-bound
48
+ * handlers; org-bound handlers may use it as a `login_hint`. */
49
+ readonly identifier?: string;
50
+ }
51
+ /**
52
+ * Context handed to a handler's `complete`. Adds the credential the user
53
+ * submitted back: an OTP code (user-bound) or an OIDC id_token (org-bound).
54
+ */
55
+ export interface MethodCompleteContext extends MethodInitiateContext {
56
+ readonly credential: string;
57
+ }
58
+ /**
59
+ * A pluggable two-phase authentication method. Models OTP (send → check)
60
+ * and OIDC (redirect → callback) under one interface. Handlers are
61
+ * **injected** into the router, so auth core depends on no protocol library.
62
+ */
63
+ export interface MethodHandler {
64
+ /** Phase 1: send an OTP, or produce a redirect URL. */
65
+ initiate(ctx: MethodInitiateContext): Promise<MethodInitiateResult>;
66
+ /** Phase 2: verify the submitted credential and resolve (provisioning
67
+ * if the handler's policy allows) the user. */
68
+ complete(ctx: MethodCompleteContext): Promise<ResolvedUser>;
69
+ }
70
+ /**
71
+ * Options for {@link createMethodRouter}.
72
+ */
73
+ export interface MethodRouterOptions {
74
+ /** Used to look up tenants and their `auth_domains`. */
75
+ db: Queryable;
76
+ /** Org-bound handlers keyed by `auth_domains.integration_type` (e.g. `{ oidc }`). */
77
+ handlers: Record<string, MethodHandler>;
78
+ /** The user-bound OTP handler (e.g. a `TwilioVerifyHandler`). Offered only
79
+ * when the tenant's `allow_otp` is true; omit it for an SSO-only product. */
80
+ otpHandler?: MethodHandler;
81
+ }
82
+ /**
83
+ * The sign-in methods available for a tenant — what the app renders on the
84
+ * sign-in surface.
85
+ */
86
+ export interface SignInOptions {
87
+ readonly tenantId: number;
88
+ /** The tenant's org-bound IdPs. Zero ⇒ OTP only; one ⇒ straight redirect;
89
+ * several ⇒ a chooser (button label `displayName`, value `authDomainId`). */
90
+ readonly authDomains: readonly AuthDomain[];
91
+ /** Whether to offer OTP: the tenant's `allow_otp` AND an `otpHandler` is set. */
92
+ readonly otpAllowed: boolean;
93
+ }
94
+ /**
95
+ * Tenant-centric sign-in dispatch. Discovery is by sub-domain → tenant (the
96
+ * app parses the Host to a slug); the router lists the tenant's IdPs and
97
+ * dispatches the chosen one by `auth_domains.integration_type`. The user-bound
98
+ * OTP path is gated by the tenant's `allow_otp` (enforced here, not just in UI).
99
+ */
100
+ export interface MethodRouter {
101
+ /** The sign-in methods for the tenant owning `tenantSlug`, or null if no
102
+ * such (live) tenant. */
103
+ signInOptions(input: {
104
+ tenantSlug: string;
105
+ }): Promise<SignInOptions | null>;
106
+ /** Org-bound phase 1 for a chosen `auth_domains` row (e.g. OIDC redirect). */
107
+ initiate(authDomainId: number): Promise<MethodInitiateResult>;
108
+ /** Org-bound phase 2 for a chosen `auth_domains` row (verify id_token, etc.). */
109
+ complete(authDomainId: number, credential: string): Promise<ResolvedUser>;
110
+ /** User-bound (OTP) phase 1. Throws {@link OtpNotAllowedError} when the
111
+ * tenant disallows OTP. */
112
+ initiateOtp(input: {
113
+ tenantId: number;
114
+ identifier: string;
115
+ }): Promise<MethodInitiateResult>;
116
+ /** User-bound (OTP) phase 2. Throws {@link OtpNotAllowedError} when the
117
+ * tenant disallows OTP. */
118
+ completeOtp(input: {
119
+ tenantId: number;
120
+ identifier: string;
121
+ credential: string;
122
+ }): Promise<ResolvedUser>;
123
+ }
124
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/methods/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C;;;;;;;;;GASG;AACH,MAAM,WAAW,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,wEAAwE;IACxE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,yCAAyC;IACzC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,+DAA+D;IAC/D,QAAQ,CAAC,iBAAiB,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UAAU,EAAE,CAAC;IAC5C,iFAAiF;IACjF,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;CAC9B;AAED;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B;8BAC0B;IAC1B,aAAa,CAAC,KAAK,EAAE;QAAE,UAAU,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC;IAC5E,8EAA8E;IAC9E,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAC9D,iFAAiF;IACjF,QAAQ,CAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1E;gCAC4B;IAC5B,WAAW,CAAC,KAAK,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAC5F;gCAC4B;IAC5B,WAAW,CAAC,KAAK,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;CACzG"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/methods/types.ts"],"names":[],"mappings":""}
@@ -1,22 +1,27 @@
1
1
  import type { Queryable } from './types.js';
2
2
  /**
3
- * Revoke a session by setting its `expires_at` to now.
3
+ * Revoke a single session by its raw token (force sign-off of that one
4
+ * session). Idempotent — revoking an unknown or already-expired session is
5
+ * not an error. The row is preserved for audit.
4
6
  *
5
- * The session row is preserved for audit — you can distinguish
6
- * "explicitly revoked" (expires_at close to created_at) from
7
- * "expired naturally" (expires_at = created_at + ttl). The
8
- * `session_authorization()` RLS function already checks
9
- * `expires_at > now()`, so the session is locked out immediately.
10
- *
11
- * Idempotent: revoking a non-existent or already-expired session
12
- * is not an error.
7
+ * @throws {InvalidInputError} If `token` is not a non-empty string.
8
+ */
9
+ export declare function revokeSession(db: Queryable, token: string): Promise<void>;
10
+ /**
11
+ * Revoke every active session belonging to a user (force sign-off
12
+ * everywhere). Use on password reset, account lockout, or a
13
+ * role/privilege change that should drop existing sessions.
13
14
  *
14
- * @example
15
- * ```ts
16
- * await revokeSession(db, sessionId);
17
- * ```
15
+ * @throws {InvalidInputError} If `userId` is not a positive integer.
16
+ */
17
+ export declare function revokeUserSessions(db: Queryable, userId: number): Promise<void>;
18
+ /**
19
+ * Revoke every active session of every user explicitly in a tenant
20
+ * (tenant-wide sign-off). Membership is resolved from `user_roles.tenant_id`
21
+ * — wildcard members (NULL tenant) are intentionally **not** signed out,
22
+ * since they belong to no single tenant.
18
23
  *
19
- * @throws {InvalidInputError} If `sessionId` is not a non-empty string.
24
+ * @throws {InvalidInputError} If `tenantId` is not a positive integer.
20
25
  */
21
- export declare function revokeSession(db: Queryable, sessionId: string): Promise<void>;
26
+ export declare function revokeTenantSessions(db: Queryable, tenantId: number): Promise<void>;
22
27
  //# sourceMappingURL=revoke-session.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"revoke-session.d.ts","sourceRoot":"","sources":["../src/revoke-session.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAS5C;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,aAAa,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKnF"}
1
+ {"version":3,"file":"revoke-session.d.ts","sourceRoot":"","sources":["../src/revoke-session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAyC5C;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAK/E;AAED;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CAAC,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKrF;AAED;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CAAC,EAAE,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKzF"}
@@ -1,33 +1,79 @@
1
1
  import { InvalidInputError } from './errors.js';
2
- const EXPIRE_SESSION = `
2
+ import { hashToken } from './internal/hash-token.js';
3
+ // Soft-revoke: set expires_at = now() so the row survives for audit but
4
+ // the session is locked out immediately (withSession/validateSession both
5
+ // reject expires_at <= now()). Guarded so we don't move an already-past
6
+ // expiry around.
7
+ const EXPIRE_BY_HASH = `
3
8
  UPDATE sessions
4
9
  SET expires_at = now()
5
10
  WHERE session_id = $1
6
- AND (expires_at IS NULL OR expires_at > now())
11
+ AND expires_at > now()
12
+ `;
13
+ const EXPIRE_BY_USER = `
14
+ UPDATE sessions s
15
+ SET expires_at = now()
16
+ FROM user_communication_methods ucm
17
+ WHERE ucm.user_communication_method_id = s.user_communication_method_id
18
+ AND ucm.user_id = $1
19
+ AND s.expires_at > now()
20
+ `;
21
+ // Tenant-wide sign-off. Membership IS user_roles.tenant_id (the contract;
22
+ // there is no user_tenants table), so the library resolves "users in
23
+ // tenant X" itself and fans out. The match is tenant_id = $1, NOT
24
+ // tenant_id IS NULL: wildcard members (NULL = all-tenants global admins /
25
+ // service principals) are not members of any one tenant and must not be
26
+ // signed out by a single tenant's sign-off.
27
+ const EXPIRE_BY_TENANT = `
28
+ UPDATE sessions s
29
+ SET expires_at = now()
30
+ FROM user_communication_methods ucm
31
+ WHERE ucm.user_communication_method_id = s.user_communication_method_id
32
+ AND s.expires_at > now()
33
+ AND ucm.user_id IN (
34
+ SELECT DISTINCT ur.user_id
35
+ FROM user_roles ur
36
+ WHERE ur.tenant_id = $1
37
+ )
7
38
  `;
8
39
  /**
9
- * Revoke a session by setting its `expires_at` to now.
40
+ * Revoke a single session by its raw token (force sign-off of that one
41
+ * session). Idempotent — revoking an unknown or already-expired session is
42
+ * not an error. The row is preserved for audit.
10
43
  *
11
- * The session row is preserved for audit — you can distinguish
12
- * "explicitly revoked" (expires_at close to created_at) from
13
- * "expired naturally" (expires_at = created_at + ttl). The
14
- * `session_authorization()` RLS function already checks
15
- * `expires_at > now()`, so the session is locked out immediately.
16
- *
17
- * Idempotent: revoking a non-existent or already-expired session
18
- * is not an error.
44
+ * @throws {InvalidInputError} If `token` is not a non-empty string.
45
+ */
46
+ export async function revokeSession(db, token) {
47
+ if (typeof token !== 'string' || token.length === 0) {
48
+ throw new InvalidInputError('token must be a non-empty string');
49
+ }
50
+ await db.query(EXPIRE_BY_HASH, [hashToken(token)]);
51
+ }
52
+ /**
53
+ * Revoke every active session belonging to a user (force sign-off
54
+ * everywhere). Use on password reset, account lockout, or a
55
+ * role/privilege change that should drop existing sessions.
19
56
  *
20
- * @example
21
- * ```ts
22
- * await revokeSession(db, sessionId);
23
- * ```
57
+ * @throws {InvalidInputError} If `userId` is not a positive integer.
58
+ */
59
+ export async function revokeUserSessions(db, userId) {
60
+ if (!Number.isInteger(userId) || userId <= 0) {
61
+ throw new InvalidInputError('userId must be a positive integer');
62
+ }
63
+ await db.query(EXPIRE_BY_USER, [userId]);
64
+ }
65
+ /**
66
+ * Revoke every active session of every user explicitly in a tenant
67
+ * (tenant-wide sign-off). Membership is resolved from `user_roles.tenant_id`
68
+ * — wildcard members (NULL tenant) are intentionally **not** signed out,
69
+ * since they belong to no single tenant.
24
70
  *
25
- * @throws {InvalidInputError} If `sessionId` is not a non-empty string.
71
+ * @throws {InvalidInputError} If `tenantId` is not a positive integer.
26
72
  */
27
- export async function revokeSession(db, sessionId) {
28
- if (typeof sessionId !== 'string' || sessionId.length === 0) {
29
- throw new InvalidInputError('sessionId must be a non-empty string');
73
+ export async function revokeTenantSessions(db, tenantId) {
74
+ if (!Number.isInteger(tenantId) || tenantId <= 0) {
75
+ throw new InvalidInputError('tenantId must be a positive integer');
30
76
  }
31
- await db.query(EXPIRE_SESSION, [sessionId]);
77
+ await db.query(EXPIRE_BY_TENANT, [tenantId]);
32
78
  }
33
79
  //# sourceMappingURL=revoke-session.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"revoke-session.js","sourceRoot":"","sources":["../src/revoke-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,cAAc,GAAG;;;;;CAKtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,EAAa,EAAE,SAAiB;IAClE,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,iBAAiB,CAAC,sCAAsC,CAAC,CAAC;IACtE,CAAC;IACD,MAAM,EAAE,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9C,CAAC"}
1
+ {"version":3,"file":"revoke-session.js","sourceRoot":"","sources":["../src/revoke-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAGrD,wEAAwE;AACxE,0EAA0E;AAC1E,wEAAwE;AACxE,iBAAiB;AACjB,MAAM,cAAc,GAAG;;;;;CAKtB,CAAC;AAEF,MAAM,cAAc,GAAG;;;;;;;CAOtB,CAAC;AAEF,0EAA0E;AAC1E,qEAAqE;AACrE,kEAAkE;AAClE,0EAA0E;AAC1E,wEAAwE;AACxE,4CAA4C;AAC5C,MAAM,gBAAgB,GAAG;;;;;;;;;;;CAWxB,CAAC;AA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