@smartcrab/contracts-public 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +202 -0
  2. package/dist/association-files.d.ts +46 -0
  3. package/dist/association-files.js +32 -0
  4. package/dist/config.d.ts +57 -0
  5. package/dist/config.js +38 -0
  6. package/dist/email.d.ts +55 -0
  7. package/dist/email.js +39 -0
  8. package/dist/index.d.ts +23 -0
  9. package/dist/index.js +23 -0
  10. package/dist/me.d.ts +297 -0
  11. package/dist/me.js +140 -0
  12. package/dist/oidc.d.ts +239 -0
  13. package/dist/oidc.js +230 -0
  14. package/dist/outcome.d.ts +19 -0
  15. package/dist/outcome.js +2 -0
  16. package/dist/passkeys.d.ts +257 -0
  17. package/dist/passkeys.js +162 -0
  18. package/dist/primitives.d.ts +60 -0
  19. package/dist/primitives.js +52 -0
  20. package/dist/redirect-uri.d.ts +25 -0
  21. package/dist/redirect-uri.js +39 -0
  22. package/dist/scopes.d.ts +30 -0
  23. package/dist/scopes.js +46 -0
  24. package/dist/social.d.ts +44 -0
  25. package/dist/social.js +35 -0
  26. package/dist/transaction-status.d.ts +53 -0
  27. package/dist/transaction-status.js +37 -0
  28. package/dist/transactions.d.ts +144 -0
  29. package/dist/transactions.js +103 -0
  30. package/package.json +43 -0
  31. package/src/association-files.test.ts +71 -0
  32. package/src/association-files.ts +46 -0
  33. package/src/config.test.ts +66 -0
  34. package/src/config.ts +62 -0
  35. package/src/email.test.ts +40 -0
  36. package/src/email.ts +50 -0
  37. package/src/index.ts +23 -0
  38. package/src/me.test.ts +116 -0
  39. package/src/me.ts +223 -0
  40. package/src/oidc.test.ts +224 -0
  41. package/src/oidc.ts +296 -0
  42. package/src/outcome.ts +17 -0
  43. package/src/passkeys.test.ts +80 -0
  44. package/src/passkeys.ts +218 -0
  45. package/src/primitives.ts +79 -0
  46. package/src/redirect-uri.test.ts +118 -0
  47. package/src/redirect-uri.ts +86 -0
  48. package/src/scopes.test.ts +51 -0
  49. package/src/scopes.ts +63 -0
  50. package/src/social.test.ts +34 -0
  51. package/src/social.ts +43 -0
  52. package/src/transaction-status.ts +44 -0
  53. package/src/transactions.test.ts +153 -0
  54. package/src/transactions.ts +129 -0
package/src/oidc.ts ADDED
@@ -0,0 +1,296 @@
1
+ import { z } from "zod";
2
+ import {
3
+ authorizationCodeSchema,
4
+ clientIdSchema,
5
+ codeChallengeSchema,
6
+ codeVerifierSchema,
7
+ httpsUrlSchema,
8
+ jtiSchema,
9
+ opaqueClientValueSchema,
10
+ redirectUriSchema,
11
+ resourceListSchema,
12
+ userIdSchema,
13
+ } from "./primitives.js";
14
+ import { scopeStringSchema } from "./scopes.js";
15
+
16
+ /**
17
+ * Authorization Server / OIDC contracts (design.md §15).
18
+ *
19
+ * Convention for this file: POST JSON bodies use `z.strictObject` (an
20
+ * unexpected key is a client bug worth surfacing). GET query-string schemas
21
+ * use the lenient `z.object` because browsers/redirect chains routinely
22
+ * append extra params (`utm_*`, etc.) that are not attacker-relevant here.
23
+ */
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Token TTLs (design.md §15.5)
27
+ // ---------------------------------------------------------------------------
28
+
29
+ const DAYS = (n: number): number => n * 24 * 60 * 60;
30
+
31
+ export const TOKEN_TTL_SECONDS = {
32
+ authorizationCode: 60,
33
+ accessToken: 300,
34
+ idToken: 300,
35
+ refreshIdle: DAYS(30),
36
+ refreshAbsolute: DAYS(90),
37
+ loginSessionIdle: DAYS(7),
38
+ loginSessionAbsolute: DAYS(30),
39
+ } as const;
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // Shared enums (design.md §15.2, §15.3, §15.4)
43
+ // ---------------------------------------------------------------------------
44
+
45
+ /** Only the Authorization Code Grant is supported (design.md §15.3: no Implicit, ROPC, Device Code). */
46
+ export const RESPONSE_TYPES = ["code"] as const;
47
+ export const responseTypeSchema = z.enum(RESPONSE_TYPES);
48
+
49
+ /** `plain` PKCE is explicitly unsupported (design.md §15.3). */
50
+ export const CODE_CHALLENGE_METHODS = ["S256"] as const;
51
+ export const codeChallengeMethodSchema = z.enum(CODE_CHALLENGE_METHODS);
52
+
53
+ export const GRANT_TYPES = ["authorization_code", "refresh_token"] as const;
54
+ export const grantTypeSchema = z.enum(GRANT_TYPES);
55
+ export type GrantType = (typeof GRANT_TYPES)[number];
56
+
57
+ /** design.md §15.4. Public clients (`web_spa`, `react_native`) never hold a secret. */
58
+ export const TOKEN_ENDPOINT_AUTH_METHODS = [
59
+ "client_secret_basic",
60
+ "client_secret_post",
61
+ "none",
62
+ ] as const;
63
+ export const tokenEndpointAuthMethodSchema = z.enum(TOKEN_ENDPOINT_AUTH_METHODS);
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // GET .../oauth2/authorize (design.md §15.1, §15.9)
67
+ // ---------------------------------------------------------------------------
68
+
69
+ /**
70
+ * Query params for the authorize endpoint. `client_id` auth fields
71
+ * (`client_secret`, Basic auth) do not appear here: authorize is a
72
+ * front-channel, browser-navigated request and never carries a client
73
+ * secret (design.md §15.4).
74
+ */
75
+ export const authorizeRequestQuerySchema = z.object({
76
+ response_type: responseTypeSchema,
77
+ client_id: clientIdSchema,
78
+ redirect_uri: redirectUriSchema,
79
+ scope: scopeStringSchema,
80
+ state: opaqueClientValueSchema,
81
+ nonce: opaqueClientValueSchema.optional(),
82
+ code_challenge: codeChallengeSchema,
83
+ code_challenge_method: codeChallengeMethodSchema,
84
+ /**
85
+ * Resource Indicators (RFC 8707). Repeated `resource=` query params are
86
+ * assembled into an array by the router before this schema runs.
87
+ */
88
+ resource: resourceListSchema.optional(),
89
+ });
90
+ export type AuthorizeRequestQuery = z.infer<typeof authorizeRequestQuerySchema>;
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // POST .../oauth2/token (design.md §15.1, §15.2, §15.4, §15.7)
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /**
97
+ * `client_id`/`client_secret` are optional here because confidential
98
+ * `web_bff` clients may instead authenticate via HTTP Basic
99
+ * (`client_secret_basic`, RFC 6749 §2.3.1) carried in the `Authorization`
100
+ * header, outside this JSON/form body.
101
+ */
102
+ const clientAuthFieldsShape = {
103
+ client_id: clientIdSchema.optional(),
104
+ client_secret: z.string().min(1).max(512).optional(),
105
+ };
106
+
107
+ export const authorizationCodeGrantRequestSchema = z.strictObject({
108
+ grant_type: z.literal("authorization_code"),
109
+ code: authorizationCodeSchema,
110
+ redirect_uri: redirectUriSchema,
111
+ code_verifier: codeVerifierSchema,
112
+ /** Resource may only narrow, never widen, the transaction's bound resources (design.md §15.7). */
113
+ resource: resourceListSchema.optional(),
114
+ ...clientAuthFieldsShape,
115
+ });
116
+ export type AuthorizationCodeGrantRequest = z.infer<typeof authorizationCodeGrantRequestSchema>;
117
+
118
+ export const refreshTokenGrantRequestSchema = z.strictObject({
119
+ grant_type: z.literal("refresh_token"),
120
+ refresh_token: z.string().min(1),
121
+ /** Narrowing only; the token endpoint rejects any scope not in the original grant (design.md §15.7). */
122
+ scope: scopeStringSchema.optional(),
123
+ resource: resourceListSchema.optional(),
124
+ ...clientAuthFieldsShape,
125
+ });
126
+ export type RefreshTokenGrantRequest = z.infer<typeof refreshTokenGrantRequestSchema>;
127
+
128
+ export const tokenRequestSchema = z.discriminatedUnion("grant_type", [
129
+ authorizationCodeGrantRequestSchema,
130
+ refreshTokenGrantRequestSchema,
131
+ ]);
132
+ export type TokenRequest = z.infer<typeof tokenRequestSchema>;
133
+
134
+ export const tokenResponseSchema = z.strictObject({
135
+ access_token: z.string().min(1),
136
+ token_type: z.literal("Bearer"),
137
+ expires_in: z.number().int().positive(),
138
+ /** Present only when `offline_access` was granted. */
139
+ refresh_token: z.string().min(1).optional(),
140
+ /** Present only when `openid` was granted. */
141
+ id_token: z.string().min(1).optional(),
142
+ scope: scopeStringSchema,
143
+ });
144
+ export type TokenResponse = z.infer<typeof tokenResponseSchema>;
145
+
146
+ // ---------------------------------------------------------------------------
147
+ // GET .../oauth2/userinfo (design.md §15.1, §15.6: email is normally omitted from the access token)
148
+ // ---------------------------------------------------------------------------
149
+
150
+ export const userinfoResponseSchema = z.strictObject({
151
+ sub: userIdSchema,
152
+ name: z.string().optional(),
153
+ email: z.email().optional(),
154
+ email_verified: z.boolean().optional(),
155
+ locale: z.string().optional(),
156
+ updated_at: z.number().int().nonnegative().optional(),
157
+ });
158
+ export type UserinfoResponse = z.infer<typeof userinfoResponseSchema>;
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // GET .../.well-known/openid-configuration (design.md §15.1)
162
+ // ---------------------------------------------------------------------------
163
+
164
+ export const oidcDiscoveryDocumentSchema = z.strictObject({
165
+ issuer: httpsUrlSchema,
166
+ authorization_endpoint: httpsUrlSchema,
167
+ token_endpoint: httpsUrlSchema,
168
+ userinfo_endpoint: httpsUrlSchema,
169
+ jwks_uri: httpsUrlSchema,
170
+ revocation_endpoint: httpsUrlSchema,
171
+ introspection_endpoint: httpsUrlSchema,
172
+ end_session_endpoint: httpsUrlSchema,
173
+ response_types_supported: z.array(responseTypeSchema),
174
+ grant_types_supported: z.array(grantTypeSchema),
175
+ code_challenge_methods_supported: z.array(codeChallengeMethodSchema),
176
+ token_endpoint_auth_methods_supported: z.array(tokenEndpointAuthMethodSchema),
177
+ scopes_supported: z.array(z.string()),
178
+ subject_types_supported: z.array(z.literal("public")),
179
+ /** design.md §15.6: ES256 only, unknown `alg` values are never accepted. */
180
+ id_token_signing_alg_values_supported: z.array(z.literal("ES256")),
181
+ claims_supported: z.array(z.string()),
182
+ });
183
+ export type OidcDiscoveryDocument = z.infer<typeof oidcDiscoveryDocumentSchema>;
184
+
185
+ // ---------------------------------------------------------------------------
186
+ // GET .../oauth2/jwks (design.md §15.1, §15.6: ES256 -> EC P-256 keys)
187
+ // ---------------------------------------------------------------------------
188
+
189
+ export const jwkSchema = z.strictObject({
190
+ kty: z.literal("EC"),
191
+ crv: z.literal("P-256"),
192
+ x: z.string().min(1),
193
+ y: z.string().min(1),
194
+ kid: z.string().min(1),
195
+ alg: z.literal("ES256"),
196
+ use: z.literal("sig"),
197
+ });
198
+ export type Jwk = z.infer<typeof jwkSchema>;
199
+
200
+ export const jwksDocumentSchema = z.strictObject({
201
+ keys: z.array(jwkSchema),
202
+ });
203
+ export type JwksDocument = z.infer<typeof jwksDocumentSchema>;
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // POST .../oauth2/introspect (RFC 7662; design.md §15.1, §15.8)
207
+ // ---------------------------------------------------------------------------
208
+
209
+ export const introspectionRequestSchema = z.strictObject({
210
+ token: z.string().min(1),
211
+ token_type_hint: z.enum(["access_token", "refresh_token"]).optional(),
212
+ ...clientAuthFieldsShape,
213
+ });
214
+ export type IntrospectionRequest = z.infer<typeof introspectionRequestSchema>;
215
+
216
+ const introspectionActiveResponseSchema = z.strictObject({
217
+ active: z.literal(true),
218
+ scope: scopeStringSchema.optional(),
219
+ client_id: clientIdSchema.optional(),
220
+ token_type: z.literal("Bearer").optional(),
221
+ exp: z.number().int().optional(),
222
+ iat: z.number().int().optional(),
223
+ nbf: z.number().int().optional(),
224
+ sub: userIdSchema.optional(),
225
+ aud: z.union([z.string(), z.array(z.string())]).optional(),
226
+ iss: httpsUrlSchema.optional(),
227
+ jti: jtiSchema.optional(),
228
+ });
229
+
230
+ /** RFC 7662 §2.2: an inactive token's response SHOULD contain only `active: false`. */
231
+ const introspectionInactiveResponseSchema = z.strictObject({
232
+ active: z.literal(false),
233
+ });
234
+
235
+ export const introspectionResponseSchema = z.union([
236
+ introspectionActiveResponseSchema,
237
+ introspectionInactiveResponseSchema,
238
+ ]);
239
+ export type IntrospectionResponse = z.infer<typeof introspectionResponseSchema>;
240
+
241
+ // ---------------------------------------------------------------------------
242
+ // POST .../oauth2/revoke (RFC 7009; design.md §15.1, §15.8)
243
+ // ---------------------------------------------------------------------------
244
+
245
+ export const revocationRequestSchema = z.strictObject({
246
+ token: z.string().min(1),
247
+ token_type_hint: z.enum(["access_token", "refresh_token"]).optional(),
248
+ ...clientAuthFieldsShape,
249
+ });
250
+ export type RevocationRequest = z.infer<typeof revocationRequestSchema>;
251
+
252
+ /**
253
+ * Always empty, always HTTP 200: design.md §15.8 requires the revocation
254
+ * endpoint to succeed even for a token that never existed, so response
255
+ * content must never leak whether the token was real.
256
+ */
257
+ export const revocationResponseSchema = z.strictObject({});
258
+ export type RevocationResponse = z.infer<typeof revocationResponseSchema>;
259
+
260
+ // ---------------------------------------------------------------------------
261
+ // GET|POST .../oauth2/logout — RP-Initiated Logout (design.md §15.1, §15.2)
262
+ // ---------------------------------------------------------------------------
263
+
264
+ export const logoutRequestSchema = z.object({
265
+ id_token_hint: z.string().optional(),
266
+ post_logout_redirect_uri: redirectUriSchema.optional(),
267
+ state: opaqueClientValueSchema.optional(),
268
+ client_id: clientIdSchema.optional(),
269
+ });
270
+ export type LogoutRequest = z.infer<typeof logoutRequestSchema>;
271
+
272
+ // ---------------------------------------------------------------------------
273
+ // OAuth error response (RFC 6749 §5.2 codes used across this file's endpoints)
274
+ // ---------------------------------------------------------------------------
275
+
276
+ export const OAUTH_ERROR_CODES = [
277
+ "invalid_request",
278
+ "invalid_client",
279
+ "invalid_grant",
280
+ "unsupported_grant_type",
281
+ "invalid_scope",
282
+ "access_denied",
283
+ "server_error",
284
+ "temporarily_unavailable",
285
+ ] as const;
286
+
287
+ export const oauthErrorCodeSchema = z.enum(OAUTH_ERROR_CODES);
288
+ export type OAuthErrorCode = (typeof OAUTH_ERROR_CODES)[number];
289
+
290
+ export const oauthErrorResponseSchema = z.strictObject({
291
+ error: oauthErrorCodeSchema,
292
+ error_description: z.string().optional(),
293
+ error_uri: httpsUrlSchema.optional(),
294
+ state: opaqueClientValueSchema.optional(),
295
+ });
296
+ export type OAuthErrorResponse = z.infer<typeof oauthErrorResponseSchema>;
package/src/outcome.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Local, dependency-free success/failure channel for pure functions in this
3
+ * package (design.md is silent on a shared type here; this mirrors
4
+ * `packages/tenant-context/src/validation.ts`'s `ParseOutcome` convention).
5
+ *
6
+ * `@smartcrab/result` is intentionally NOT a dependency of this package
7
+ * (its source requires DOM/workers ambient types this package does not carry
8
+ * and does not need). Any function in this package that can fail returns this
9
+ * shape instead of throwing.
10
+ */
11
+ export type Outcome<T, E> =
12
+ | { readonly ok: true; readonly value: T }
13
+ | { readonly ok: false; readonly error: E };
14
+
15
+ export const ok = <T, E>(value: T): Outcome<T, E> => ({ ok: true, value });
16
+
17
+ export const err = <T, E>(error: E): Outcome<T, E> => ({ ok: false, error });
@@ -0,0 +1,80 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ passkeyAuthenticationOptionsResponseSchema,
4
+ passkeyRegistrationOptionsRequestSchema,
5
+ passkeyRegistrationOptionsResponseSchema,
6
+ } from "./passkeys.js";
7
+
8
+ const CHALLENGE = "a".repeat(32);
9
+
10
+ describe("passkeyRegistrationOptionsRequestSchema", () => {
11
+ test("has no body", () => {
12
+ expect(passkeyRegistrationOptionsRequestSchema.safeParse({}).success).toBe(true);
13
+ expect(
14
+ passkeyRegistrationOptionsRequestSchema.safeParse({ email: "x@example.com" }).success,
15
+ ).toBe(false);
16
+ });
17
+ });
18
+
19
+ describe("passkeyRegistrationOptionsResponseSchema (design.md §17.1)", () => {
20
+ const base = {
21
+ rp: { id: "env_x.login.example-auth.com", name: "Example Auth" },
22
+ user: { id: "b".repeat(22), name: "user-handle", displayName: "Ada" },
23
+ challenge: CHALLENGE,
24
+ pubKeyCredParams: [{ type: "public-key", alg: -7 }],
25
+ authenticatorSelection: { residentKey: "required", userVerification: "required" },
26
+ attestation: "none",
27
+ };
28
+
29
+ test("accepts the platform-fixed configuration", () => {
30
+ expect(passkeyRegistrationOptionsResponseSchema.safeParse(base).success).toBe(true);
31
+ });
32
+
33
+ test("rejects residentKey values other than 'required'", () => {
34
+ const parsed = passkeyRegistrationOptionsResponseSchema.safeParse({
35
+ ...base,
36
+ authenticatorSelection: { residentKey: "preferred", userVerification: "required" },
37
+ });
38
+ expect(parsed.success).toBe(false);
39
+ });
40
+
41
+ test("rejects attestation values other than 'none'", () => {
42
+ expect(
43
+ passkeyRegistrationOptionsResponseSchema.safeParse({ ...base, attestation: "direct" })
44
+ .success,
45
+ ).toBe(false);
46
+ });
47
+
48
+ test("allows platform authenticator or security key (authenticatorAttachment is not fixed)", () => {
49
+ for (const attachment of ["platform", "cross-platform", undefined]) {
50
+ const parsed = passkeyRegistrationOptionsResponseSchema.safeParse({
51
+ ...base,
52
+ authenticatorSelection: {
53
+ ...base.authenticatorSelection,
54
+ ...(attachment !== undefined ? { authenticatorAttachment: attachment } : {}),
55
+ },
56
+ });
57
+ expect(parsed.success).toBe(true);
58
+ }
59
+ });
60
+ });
61
+
62
+ describe("passkeyAuthenticationOptionsResponseSchema (design.md §17.2)", () => {
63
+ test("accepts the discoverable-credential default flow with no allowCredentials", () => {
64
+ const parsed = passkeyAuthenticationOptionsResponseSchema.safeParse({
65
+ challenge: CHALLENGE,
66
+ rpId: "env_x.login.example-auth.com",
67
+ userVerification: "required",
68
+ });
69
+ expect(parsed.success).toBe(true);
70
+ });
71
+
72
+ test("rejects userVerification values other than 'required'", () => {
73
+ const parsed = passkeyAuthenticationOptionsResponseSchema.safeParse({
74
+ challenge: CHALLENGE,
75
+ rpId: "env_x.login.example-auth.com",
76
+ userVerification: "preferred",
77
+ });
78
+ expect(parsed.success).toBe(false);
79
+ });
80
+ });
@@ -0,0 +1,218 @@
1
+ import { z } from "zod";
2
+ import { isoDateTimeSchema, passkeyIdSchema } from "./primitives.js";
3
+ import { transactionAuthResultResponseSchema } from "./transaction-status.js";
4
+
5
+ /**
6
+ * Passkey (WebAuthn) contracts (design.md §17).
7
+ *
8
+ * `@simplewebauthn/server`/`@simplewebauthn/browser` are NOT dependencies of
9
+ * this package (see assignment notes: only zod, tenant-context, identifiers
10
+ * are available here), so the WebAuthn JSON shapes below are hand-written to
11
+ * the WebAuthn Level 3 / `@simplewebauthn` wire format rather than imported.
12
+ * They are intentionally permissive about vendor/algorithm extension points
13
+ * and strict about the fields design.md §17.1 fixes platform-wide:
14
+ * `residentKey: "required"`, `userVerification: "required"`,
15
+ * `attestationType: "none"`.
16
+ */
17
+
18
+ const base64UrlStringSchema = z
19
+ .string()
20
+ .min(1)
21
+ .regex(/^[A-Za-z0-9_-]+$/);
22
+
23
+ const AUTHENTICATOR_TRANSPORTS = ["ble", "hybrid", "internal", "nfc", "usb"] as const;
24
+ const transportSchema = z.enum(AUTHENTICATOR_TRANSPORTS);
25
+
26
+ const authenticatorAttachmentSchema = z.enum(["platform", "cross-platform"]);
27
+
28
+ const rpEntitySchema = z.strictObject({
29
+ id: z.string().min(1),
30
+ name: z.string().min(1),
31
+ });
32
+
33
+ /** design.md §17.1: "user handleへメールアドレスを入れない" — always an opaque handle. */
34
+ const userEntitySchema = z.strictObject({
35
+ id: base64UrlStringSchema,
36
+ name: z.string().min(1),
37
+ displayName: z.string().min(1),
38
+ });
39
+
40
+ const pubKeyCredParamSchema = z.strictObject({
41
+ type: z.literal("public-key"),
42
+ alg: z.number().int(),
43
+ });
44
+
45
+ const credentialDescriptorSchema = z.strictObject({
46
+ id: base64UrlStringSchema,
47
+ type: z.literal("public-key"),
48
+ transports: z.array(transportSchema).optional(),
49
+ });
50
+
51
+ /** design.md §17.1: residentKey/userVerification are fixed, not client-configurable. */
52
+ const authenticatorSelectionSchema = z.strictObject({
53
+ authenticatorAttachment: authenticatorAttachmentSchema.optional(),
54
+ residentKey: z.literal("required"),
55
+ userVerification: z.literal("required"),
56
+ });
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // Registration (design.md §17.1)
60
+ // ---------------------------------------------------------------------------
61
+
62
+ /**
63
+ * design.md §8.3: an explicit RP ID (hostname) for the ceremony. Native apps
64
+ * send the domain baked into their binary (Android asset_statements, iOS
65
+ * webcredentials); it must be the active or a still-honoured legacy RP ID.
66
+ */
67
+ export const passkeyRpIdSchema = z.string().min(1);
68
+
69
+ /** Registration options are derived from transaction/session state; only the RP ID may be named. */
70
+ export const passkeyRegistrationOptionsRequestSchema = z.strictObject({
71
+ rp_id: passkeyRpIdSchema.optional(),
72
+ });
73
+ export type PasskeyRegistrationOptionsRequest = z.infer<
74
+ typeof passkeyRegistrationOptionsRequestSchema
75
+ >;
76
+
77
+ export const passkeyRegistrationOptionsResponseSchema = z.strictObject({
78
+ rp: rpEntitySchema,
79
+ user: userEntitySchema,
80
+ challenge: base64UrlStringSchema,
81
+ pubKeyCredParams: z.array(pubKeyCredParamSchema).min(1),
82
+ timeout: z.number().int().positive().optional(),
83
+ /** Existing credentials to exclude, preventing duplicate registration on one authenticator. */
84
+ excludeCredentials: z.array(credentialDescriptorSchema).optional(),
85
+ authenticatorSelection: authenticatorSelectionSchema,
86
+ attestation: z.literal("none"),
87
+ });
88
+ export type PasskeyRegistrationOptionsResponse = z.infer<
89
+ typeof passkeyRegistrationOptionsResponseSchema
90
+ >;
91
+
92
+ const registrationCredentialResponseSchema = z.strictObject({
93
+ clientDataJSON: base64UrlStringSchema,
94
+ attestationObject: base64UrlStringSchema,
95
+ transports: z.array(transportSchema).optional(),
96
+ publicKeyAlgorithm: z.number().int().optional(),
97
+ publicKey: base64UrlStringSchema.optional(),
98
+ authenticatorData: base64UrlStringSchema.optional(),
99
+ });
100
+
101
+ export const passkeyRegistrationCredentialSchema = z.strictObject({
102
+ id: base64UrlStringSchema,
103
+ rawId: base64UrlStringSchema,
104
+ type: z.literal("public-key"),
105
+ response: registrationCredentialResponseSchema,
106
+ authenticatorAttachment: authenticatorAttachmentSchema.optional(),
107
+ clientExtensionResults: z.record(z.string(), z.unknown()).optional(),
108
+ });
109
+ export type PasskeyRegistrationCredential = z.infer<typeof passkeyRegistrationCredentialSchema>;
110
+
111
+ /** Shared by both the transaction-scoped and `/v1/me`-scoped registration/verify routes. */
112
+ export const passkeyRegistrationVerifyRequestSchema = z.strictObject({
113
+ credential: passkeyRegistrationCredentialSchema,
114
+ /** User-supplied label, e.g. "iPhone 15" (design.md §12.5 `passkeys.name NULLABLE`). */
115
+ name: z.string().min(1).max(100).optional(),
116
+ });
117
+ export type PasskeyRegistrationVerifyRequest = z.infer<
118
+ typeof passkeyRegistrationVerifyRequestSchema
119
+ >;
120
+
121
+ export const PASSKEY_DEVICE_TYPES = ["single_device", "multi_device"] as const;
122
+ export const passkeyDeviceTypeSchema = z.enum(PASSKEY_DEVICE_TYPES);
123
+
124
+ /** Public projection of the `passkeys` table row (design.md §12.5), minus `credential_id`/`public_key`/`sign_count`. */
125
+ export const passkeySummarySchema = z.strictObject({
126
+ passkey_id: passkeyIdSchema,
127
+ name: z.string().nullable(),
128
+ created_at: isoDateTimeSchema,
129
+ last_used_at: isoDateTimeSchema.nullable(),
130
+ device_type: passkeyDeviceTypeSchema.nullable(),
131
+ backed_up: z.boolean(),
132
+ transports: z.array(transportSchema).optional(),
133
+ });
134
+ export type PasskeySummary = z.infer<typeof passkeySummarySchema>;
135
+
136
+ /** Transaction-scoped registration verify additionally reports transaction progress. */
137
+ export const transactionPasskeyRegistrationVerifyResponseSchema =
138
+ transactionAuthResultResponseSchema.extend({
139
+ passkey: passkeySummarySchema,
140
+ });
141
+ export type TransactionPasskeyRegistrationVerifyResponse = z.infer<
142
+ typeof transactionPasskeyRegistrationVerifyResponseSchema
143
+ >;
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // Authentication (design.md §17.2)
147
+ // ---------------------------------------------------------------------------
148
+
149
+ /**
150
+ * design.md §17.2: "ユーザー名なしのdiscoverable credentialフローを標準に
151
+ * する。任意でメール入力後のallowCredentials絞り込みも提供するが、アカウン
152
+ * ト列挙を起こさないレスポンスにする." `email` is optional and, like Email
153
+ * OTP, must never change the response shape based on whether it matches an
154
+ * account.
155
+ */
156
+ export const passkeyAuthenticationRpSchema = z.enum(["active", "legacy"]);
157
+ export type PasskeyAuthenticationRp = z.infer<typeof passkeyAuthenticationRpSchema>;
158
+
159
+ export const passkeyAuthenticationOptionsRequestSchema = z
160
+ .strictObject({
161
+ email: z.email().optional(),
162
+ /** design.md §8.3: request the assertion for the legacy RP ID during migration (Hosted Login). */
163
+ rp: passkeyAuthenticationRpSchema.optional(),
164
+ /** design.md §8.3: explicit RP ID; mutually exclusive with `rp`. */
165
+ rp_id: passkeyRpIdSchema.optional(),
166
+ })
167
+ .refine((body) => body.rp === undefined || body.rp_id === undefined, {
168
+ message: "rp and rp_id are mutually exclusive",
169
+ });
170
+ export type PasskeyAuthenticationOptionsRequest = z.input<
171
+ typeof passkeyAuthenticationOptionsRequestSchema
172
+ >;
173
+
174
+ export const passkeyAuthenticationOptionsResponseSchema = z.strictObject({
175
+ challenge: base64UrlStringSchema,
176
+ timeout: z.number().int().positive().optional(),
177
+ rpId: z.string().min(1),
178
+ /** Only present when `email` narrowed the credential set; omitted for the discoverable-credential default flow. */
179
+ allowCredentials: z.array(credentialDescriptorSchema).optional(),
180
+ userVerification: z.literal("required"),
181
+ });
182
+ export type PasskeyAuthenticationOptionsResponse = z.infer<
183
+ typeof passkeyAuthenticationOptionsResponseSchema
184
+ >;
185
+
186
+ const authenticationCredentialResponseSchema = z.strictObject({
187
+ clientDataJSON: base64UrlStringSchema,
188
+ authenticatorData: base64UrlStringSchema,
189
+ signature: base64UrlStringSchema,
190
+ /** Present for discoverable-credential (usernameless) authentication. */
191
+ userHandle: base64UrlStringSchema.optional(),
192
+ });
193
+
194
+ export const passkeyAuthenticationCredentialSchema = z.strictObject({
195
+ id: base64UrlStringSchema,
196
+ rawId: base64UrlStringSchema,
197
+ type: z.literal("public-key"),
198
+ response: authenticationCredentialResponseSchema,
199
+ authenticatorAttachment: authenticatorAttachmentSchema.optional(),
200
+ clientExtensionResults: z.record(z.string(), z.unknown()).optional(),
201
+ });
202
+ export type PasskeyAuthenticationCredential = z.infer<typeof passkeyAuthenticationCredentialSchema>;
203
+
204
+ export const passkeyAuthenticationVerifyRequestSchema = z.strictObject({
205
+ credential: passkeyAuthenticationCredentialSchema,
206
+ });
207
+ export type PasskeyAuthenticationVerifyRequest = z.infer<
208
+ typeof passkeyAuthenticationVerifyRequestSchema
209
+ >;
210
+
211
+ /**
212
+ * design.md §16.3: authentication verify must NOT return tokens directly,
213
+ * only a transaction status ack (`POST .../complete` returns the code).
214
+ */
215
+ export const passkeyAuthenticationVerifyResponseSchema = transactionAuthResultResponseSchema;
216
+ export type PasskeyAuthenticationVerifyResponse = z.infer<
217
+ typeof passkeyAuthenticationVerifyResponseSchema
218
+ >;
@@ -0,0 +1,79 @@
1
+ import { idPattern } from "@smartcrab/identifiers";
2
+ import { z } from "zod";
3
+
4
+ /**
5
+ * Shared primitives for the public authentication API (design.md §16, §15).
6
+ *
7
+ * Resource IDs reuse the exact `<prefix>_<32 base32url chars>` patterns from
8
+ * `@smartcrab/identifiers` (design.md §7.5) so this package never
9
+ * hand-rolls a competing regex.
10
+ */
11
+
12
+ export const clientIdSchema = z.string().regex(idPattern("client"));
13
+ export type ClientId = z.infer<typeof clientIdSchema>;
14
+
15
+ export const transactionIdSchema = z.string().regex(idPattern("transaction"));
16
+ export type TransactionId = z.infer<typeof transactionIdSchema>;
17
+
18
+ export const userIdSchema = z.string().regex(idPattern("user"));
19
+ export type UserId = z.infer<typeof userIdSchema>;
20
+
21
+ export const sessionIdSchema = z.string().regex(idPattern("session"));
22
+ export type SessionId = z.infer<typeof sessionIdSchema>;
23
+
24
+ export const passkeyIdSchema = z.string().regex(idPattern("passkey"));
25
+ export type PasskeyId = z.infer<typeof passkeyIdSchema>;
26
+
27
+ export const identityIdSchema = z.string().regex(idPattern("identity"));
28
+ export type IdentityId = z.infer<typeof identityIdSchema>;
29
+
30
+ export const webhookIdSchema = z.string().regex(idPattern("webhook"));
31
+ export type WebhookId = z.infer<typeof webhookIdSchema>;
32
+
33
+ /** `ac_...` — one-time authorization code (design.md §16.3 example). */
34
+ export const authorizationCodeSchema = z.string().regex(idPattern("authorizationCode"));
35
+ export type AuthorizationCode = z.infer<typeof authorizationCodeSchema>;
36
+
37
+ /** `jti_...` — JWT ID, used by the introspection response (design.md §15.6 example). */
38
+ export const jtiSchema = z.string().regex(idPattern("jti"));
39
+ export type Jti = z.infer<typeof jtiSchema>;
40
+
41
+ /** Issuer/endpoint URLs are always `https://` (design.md §8). */
42
+ export const httpsUrlSchema = z.url({ protocol: /^https$/ });
43
+
44
+ /**
45
+ * Redirect URIs are opaque, byte-for-byte compared strings (design.md §15.9):
46
+ * they may be `https://...` (web, Universal/App Links) or a non-http(s)
47
+ * custom scheme (React Native, e.g. `com.customer.app:/oauth/callback`).
48
+ * Structural/scheme rules are enforced by `validateRedirectUri`
49
+ * (./redirect-uri.js) against the client's registered list, not by this
50
+ * shape check alone.
51
+ */
52
+ export const redirectUriSchema = z.string().min(1).max(2048);
53
+
54
+ /**
55
+ * Opaque values the client supplies and the server stores only as a MAC
56
+ * (design.md §16.1: "`state`と`nonce`はMACのみ保存する。"). Bounded to keep
57
+ * request bodies small; the value itself carries no semantics for us.
58
+ */
59
+ export const opaqueClientValueSchema = z.string().min(1).max(512);
60
+
61
+ /** RFC 7636 §4.2: 43-char base64url(SHA-256(verifier)) — always 43 chars, never padded. */
62
+ export const codeChallengeSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/);
63
+
64
+ /** RFC 7636 §4.1: 43-128 unreserved characters. */
65
+ export const codeVerifierSchema = z.string().regex(/^[A-Za-z0-9._~-]{43,128}$/);
66
+
67
+ /** ISO 8601 UTC timestamp, e.g. `2026-08-02T08:10:00Z` (design.md §16.1 example). */
68
+ export const isoDateTimeSchema = z.iso.datetime();
69
+
70
+ /** Email OTP is always 6 numeric digits (design.md §18.2). */
71
+ export const emailOtpCodeSchema = z.string().regex(/^[0-9]{6}$/);
72
+
73
+ /**
74
+ * Resource indicators (RFC 8707) this platform issues bindings for are
75
+ * always HTTPS APIs (design.md §16.1 example: `https://api.customer.example`).
76
+ * Capped defensively; the platform does not document an upper bound but an
77
+ * unbounded array is an abuse vector in a public, unauthenticated endpoint.
78
+ */
79
+ export const resourceListSchema = z.array(httpsUrlSchema).max(20);