@wtfalch/keys 0.7.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +349 -7
  2. package/dist/held/index.d.ts +116 -6
  3. package/dist/held/index.js +247 -25
  4. package/dist/held/schema.d.ts +17 -0
  5. package/dist/held/schema.js +12 -0
  6. package/dist/held/shred.d.ts +6 -0
  7. package/dist/held/shred.js +6 -0
  8. package/dist/held-edge/index.d.ts +17 -2
  9. package/dist/held-edge/index.js +51 -9
  10. package/dist/host/audit-endpoint.js +2 -8
  11. package/dist/host/company-registrar-keys.d.ts +106 -0
  12. package/dist/host/company-registrar-keys.js +211 -0
  13. package/dist/host/events.d.ts +19 -3
  14. package/dist/host/events.js +55 -20
  15. package/dist/host/index.d.ts +15 -1
  16. package/dist/host/index.js +15 -1
  17. package/dist/host/native-build.d.ts +126 -0
  18. package/dist/host/native-build.js +322 -0
  19. package/dist/host/registrar.d.ts +87 -0
  20. package/dist/host/registrar.js +284 -0
  21. package/dist/host/rotation-sweep.d.ts +56 -0
  22. package/dist/host/rotation-sweep.js +89 -0
  23. package/dist/issued/encoding.d.ts +4 -0
  24. package/dist/issued/encoding.js +22 -0
  25. package/dist/issued/index.d.ts +148 -7
  26. package/dist/issued/index.js +320 -34
  27. package/dist/issued/resign.d.ts +16 -0
  28. package/dist/issued/resign.js +55 -2
  29. package/dist/issued/tables.d.ts +38 -0
  30. package/dist/issued/tables.js +6 -0
  31. package/dist/issued/verify.d.ts +14 -3
  32. package/dist/issued/verify.js +10 -3
  33. package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
  34. package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
  35. package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
  36. package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
  37. package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
  38. package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
  39. package/dist/service/body.d.ts +21 -0
  40. package/dist/service/body.js +128 -0
  41. package/dist/service/errors.d.ts +24 -0
  42. package/dist/service/errors.js +89 -0
  43. package/dist/service/handler.d.ts +35 -0
  44. package/dist/service/handler.js +328 -0
  45. package/dist/service/index.d.ts +7 -0
  46. package/dist/service/index.js +7 -0
  47. package/dist/service/policy.d.ts +130 -0
  48. package/dist/service/policy.js +123 -0
  49. package/dist/service/timeout.d.ts +6 -0
  50. package/dist/service/timeout.js +34 -0
  51. package/dist/testing/index.d.ts +3 -0
  52. package/dist/testing/index.js +3 -0
  53. package/dist/webhooks.d.ts +40 -17
  54. package/dist/webhooks.js +70 -26
  55. package/dist/worker-contract.d.ts +43 -6
  56. package/dist/worker-contract.js +37 -0
  57. package/dist/worker.d.ts +1 -1
  58. package/dist/worker.js +7 -28
  59. package/package.json +21 -3
@@ -0,0 +1,284 @@
1
+ import { and, eq, gt, isNull, ne } from 'drizzle-orm';
2
+ import { keysIssuedCredentials } from '../issued/tables.js';
3
+ import { ID_PATTERN } from '../worker-contract.js';
4
+ /** Every member of `RegistrarRefusalReason`. Adding one is a major change after 1.0.0. */
5
+ export const REGISTRAR_REFUSAL_REASONS = [
6
+ 'bad_app_name',
7
+ 'company_key_invalid',
8
+ 'company_key_not_a_registrar',
9
+ 'app_held_by_another_key',
10
+ 'rate_limited',
11
+ ];
12
+ /**
13
+ * `registrar:<organisationId>:<appName>` -- deterministic, so a repeat
14
+ * `registerApp` call is the same `issue()` idempotency key, and `revokeApp`
15
+ * can find the row without a table of its own. A company key with no
16
+ * `organisation_id` (older than 0.10.0) uses its own credential id in that
17
+ * place, as before. Both components are `ID_PATTERN`-checked before this is
18
+ * built, so neither can smuggle a colon in and reach across the boundary
19
+ * between them.
20
+ */
21
+ function scopeKey(scope, appName) {
22
+ return `registrar:${scope}:${appName}`;
23
+ }
24
+ export function createRegistrar(options) {
25
+ const { db, issuer, appGrants, appTtlMs, isRegistrarGrant } = options;
26
+ // A registrar that hands out registrar-capable credentials would let a
27
+ // company key mint further company keys, which the lineage scoping below
28
+ // is not built to contain. Refuse at construction, not on first use.
29
+ if (appGrants.some(isRegistrarGrant)) {
30
+ throw new Error('createRegistrar: appGrants contains a grant isRegistrarGrant accepts; an app credential must never be able to act as a registrar');
31
+ }
32
+ const now = options.now ?? (() => Date.now());
33
+ async function checkCompanyKey(companySecret) {
34
+ const checked = await issuer.check(companySecret);
35
+ if (!checked.ok) {
36
+ // Never surfaces *why* a presented secret failed (not found, bad
37
+ // signature, revoked, expired, wrong secret) -- the Worker's own
38
+ // boundary collapses the same way (`credential_invalid` covers
39
+ // several underlying reasons) so a caller gains nothing by probing.
40
+ if (checked.reason === 'rate_limited') {
41
+ return { ok: false, reason: 'rate_limited', retryAfterMs: checked.retryAfterMs };
42
+ }
43
+ return { ok: false, reason: 'company_key_invalid' };
44
+ }
45
+ // An app key and a revoked key read alike, so a caller cannot tell them apart.
46
+ if (!checked.grants.some(isRegistrarGrant)) {
47
+ return { ok: false, reason: 'company_key_invalid' };
48
+ }
49
+ return {
50
+ ok: true,
51
+ companyCredentialId: checked.id,
52
+ scope: checked.organisationId ?? checked.id,
53
+ environment: checked.environment,
54
+ };
55
+ }
56
+ /** True when a different, live key of the same organisation already holds this app name. */
57
+ async function heldByAnotherKey(scope, companyCredentialId, appName) {
58
+ const [row] = await db
59
+ .select({ id: keysIssuedCredentials.id })
60
+ .from(keysIssuedCredentials)
61
+ .where(and(eq(keysIssuedCredentials.idempotencyKey, scopeKey(scope, appName)), ne(keysIssuedCredentials.issuedById, companyCredentialId), isNull(keysIssuedCredentials.revokedAt), gt(keysIssuedCredentials.expiresAt, now())))
62
+ .limit(1);
63
+ return row !== undefined;
64
+ }
65
+ async function registerApp(companySecret, appName) {
66
+ if (!ID_PATTERN.test(appName))
67
+ return { ok: false, reason: 'bad_app_name' };
68
+ const scoped = await checkCompanyKey(companySecret);
69
+ if (!scoped.ok)
70
+ return scoped;
71
+ if (await heldByAnotherKey(scoped.scope, scoped.companyCredentialId, appName)) {
72
+ return { ok: false, reason: 'app_held_by_another_key' };
73
+ }
74
+ // An app cannot outlive its company key (`issue()` refuses it), so a key
75
+ // with less life left than `appTtlMs` gives its apps the rest of its own.
76
+ const [company] = await db
77
+ .select({ expiresAt: keysIssuedCredentials.expiresAt })
78
+ .from(keysIssuedCredentials)
79
+ .where(eq(keysIssuedCredentials.id, scoped.companyCredentialId))
80
+ .limit(1);
81
+ const result = await issuer.issue({
82
+ grants: appGrants,
83
+ minter: scoped.companyCredentialId,
84
+ expiresAt: Math.min(now() + appTtlMs, company?.expiresAt ?? Number.POSITIVE_INFINITY),
85
+ environment: scoped.environment,
86
+ idempotencyKey: scopeKey(scoped.scope, appName),
87
+ replaceStale: true,
88
+ });
89
+ if (!result.ok)
90
+ return result;
91
+ return { ok: true, id: result.id, secret: result.secret };
92
+ }
93
+ async function revokeApp(companySecret, appName) {
94
+ if (!ID_PATTERN.test(appName))
95
+ return { ok: false, reason: 'bad_app_name' };
96
+ const scoped = await checkCompanyKey(companySecret);
97
+ if (!scoped.ok)
98
+ return scoped;
99
+ const [row] = await db
100
+ .select({
101
+ id: keysIssuedCredentials.id,
102
+ issuedById: keysIssuedCredentials.issuedById,
103
+ revokedAt: keysIssuedCredentials.revokedAt,
104
+ })
105
+ .from(keysIssuedCredentials)
106
+ .where(and(eq(keysIssuedCredentials.idempotencyKey, scopeKey(scoped.scope, appName)), eq(keysIssuedCredentials.issuedById, scoped.companyCredentialId)))
107
+ .limit(1);
108
+ // Scoped twice: by the idempotency key (unique per company+app already)
109
+ // and, belt and suspenders, by `issuedById` -- so a lookup can never
110
+ // reach a row this company's key did not itself mint.
111
+ if (!row || row.issuedById !== scoped.companyCredentialId) {
112
+ return { ok: false, reason: 'app_not_found' };
113
+ }
114
+ if (row.revokedAt !== null)
115
+ return { ok: true, revoked: false };
116
+ // No app credential this registrar mints is ever a minter of its own --
117
+ // it is always a leaf under the company credential -- so cascading has
118
+ // nothing to reach beyond the row itself.
119
+ const revoked = await issuer.revokeForCompany(row.id, { cascade: false });
120
+ if (!revoked.ok)
121
+ return revoked;
122
+ return { ok: true, revoked: revoked.revoked.length > 0 };
123
+ }
124
+ return { registerApp, revokeApp };
125
+ }
126
+ // ---------------------------------------------------------------------------
127
+ // The HTTP route
128
+ // ---------------------------------------------------------------------------
129
+ const PATH_PATTERN = /^\/v1\/keys\/registrar\/apps\/([^/]+)$/;
130
+ const BEARER_PATTERN = /^Bearer (.+)$/;
131
+ function statusForRegistrar(reason) {
132
+ switch (reason) {
133
+ case 'bad_app_name':
134
+ case 'expires_at_required':
135
+ case 'expires_at_past':
136
+ case 'environment_mismatch':
137
+ case 'expires_after_minter':
138
+ return 400;
139
+ case 'company_key_invalid':
140
+ return 401;
141
+ case 'company_key_not_a_registrar':
142
+ case 'protected_credential':
143
+ case 'purpose_unknown':
144
+ case 'purpose_not_allowed':
145
+ case 'organisation_mismatch':
146
+ case 'minter_not_found':
147
+ case 'minter_revoked':
148
+ case 'minter_expired':
149
+ return 403;
150
+ case 'rate_limited':
151
+ return 429;
152
+ case 'app_not_found':
153
+ return 404;
154
+ case 'app_held_by_another_key':
155
+ case 'idempotency_conflict':
156
+ case 'idempotent_row_revoked':
157
+ case 'idempotent_row_expired':
158
+ return 409;
159
+ // Raw Worker codes surfaced by `issue()`: none of them is something the
160
+ // caller can fix by changing the request. They are a fault between this
161
+ // host and its signing Worker, so they answer 502, not a refusal.
162
+ case 'credential_invalid':
163
+ case 'credential_expired':
164
+ case 'credential_revoked':
165
+ case 'grant_missing':
166
+ case 'bad_request':
167
+ case 'aad_mismatch':
168
+ case 'unknown_generation':
169
+ case 'bad_minter_signature':
170
+ case 'minter_exceeded':
171
+ case 'bad_worker_signature':
172
+ case 'lineage_mismatch':
173
+ case 'bad_old_signature':
174
+ case 'unlogged_row':
175
+ case 'not_in_lineage':
176
+ case 'unreachable':
177
+ return 502;
178
+ default: {
179
+ const unreachable = reason;
180
+ void unreachable;
181
+ // A reason this build does not know (a newer issuer): not a refusal.
182
+ return 502;
183
+ }
184
+ }
185
+ }
186
+ const MESSAGES = {
187
+ bad_app_name: 'The app name is not valid. Use letters, digits, dashes, dots or underscores, then try again.',
188
+ company_key_invalid: 'The company key was not accepted. Check that you are sending the current key as a Bearer token; if it was rotated or revoked, ask for a new one.',
189
+ company_key_not_a_registrar: 'This key belongs to an app, not to a company, so it cannot register apps. Use the company key.',
190
+ rate_limited: 'Too many attempts. Please wait a little and try again.',
191
+ app_held_by_another_key: 'Another key of this company already registered an app with that name. Use a different name, or ask that key to remove it first.',
192
+ protected_credential: 'This key is a company root and cannot be removed here. We can roll it to a new secret for you instead.',
193
+ purpose_unknown: 'We have not yet marked what this key is for, so we left it as it is. Ask the operator to finish setting it up, then try again.',
194
+ app_not_found: 'No app with that name is registered under this company key.',
195
+ expires_at_required: 'The app credential could not be given an expiry. Contact the operator.',
196
+ expires_at_past: 'The app credential could not be given an expiry. Contact the operator.',
197
+ environment_mismatch: 'The company key and the app credential are for different environments.',
198
+ minter_not_found: 'The company key is no longer known. Ask for a new company key and register again.',
199
+ minter_revoked: 'The company key has been revoked. Ask for a new company key and register again.',
200
+ minter_expired: 'The company key has expired. Ask for a new company key and register again.',
201
+ minter_exceeded: 'The company key needs to be renewed before it can register this app. Ask the operator for a new company key and register again.',
202
+ };
203
+ const UNAVAILABLE_MESSAGE = 'The key service could not complete this request. Nothing was changed that you need to undo; try again in a moment, and contact the operator if it keeps happening.';
204
+ function messageFor(reason) {
205
+ return MESSAGES[reason] ?? UNAVAILABLE_MESSAGE;
206
+ }
207
+ /** Every answer, success or not, may carry a secret or tell about one: never cacheable. */
208
+ function jsonHeaders() {
209
+ return new Headers({ 'content-type': 'application/json', 'cache-control': 'no-store' });
210
+ }
211
+ function errorResponse(reason, retryAfterMs) {
212
+ const headers = jsonHeaders();
213
+ if (retryAfterMs !== undefined) {
214
+ headers.set('retry-after', String(Math.ceil(retryAfterMs / 1000)));
215
+ }
216
+ const status = statusForRegistrar(reason);
217
+ return new Response(JSON.stringify({ error: reason, message: messageFor(reason) }), {
218
+ status,
219
+ headers,
220
+ });
221
+ }
222
+ function unavailableResponse() {
223
+ return new Response(JSON.stringify({ error: 'unavailable', message: UNAVAILABLE_MESSAGE }), {
224
+ status: 502,
225
+ headers: jsonHeaders(),
226
+ });
227
+ }
228
+ function okResponse(body) {
229
+ return new Response(JSON.stringify(body), { status: 200, headers: jsonHeaders() });
230
+ }
231
+ function plainResponse(status) {
232
+ return new Response(null, { status, headers: { 'cache-control': 'no-store' } });
233
+ }
234
+ /**
235
+ * `registrarEndpoint({ ... })` returns a fetch-shaped handler -- wire it
236
+ * directly as a route, e.g.
237
+ * `export const PUT = registrarEndpoint({ db, issuer, appGrants, appTtlMs, isRegistrarGrant });`
238
+ * (the same handler again as `export const DELETE`).
239
+ * `PUT /v1/keys/registrar/apps/<appName>` registers (or idempotently
240
+ * re-registers) that app under the caller's company; `DELETE` on the same
241
+ * path revokes it. The caller's company credential is the bearer token,
242
+ * same as every other credential this package already checks -- there is
243
+ * no separate registrar-specific auth scheme to configure.
244
+ *
245
+ * Errors answer `{ error, message }` (the auth broker's shape). A database
246
+ * or issuer failure that throws answers 502 `unavailable`, never a refusal
247
+ * such as `company_key_invalid`.
248
+ */
249
+ export function registrarEndpoint(options) {
250
+ const registrar = createRegistrar(options);
251
+ return async function handleKeysRegistrar(request) {
252
+ const match = PATH_PATTERN.exec(new URL(request.url).pathname);
253
+ if (!match)
254
+ return plainResponse(404);
255
+ const appName = match[1];
256
+ const auth = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
257
+ if (!auth)
258
+ return errorResponse('company_key_invalid');
259
+ const companySecret = auth[1];
260
+ try {
261
+ if (request.method === 'PUT') {
262
+ const result = await registrar.registerApp(companySecret, appName);
263
+ if (!result.ok)
264
+ return errorResponse(result.reason, result.retryAfterMs);
265
+ return okResponse({ id: result.id, secret: result.secret });
266
+ }
267
+ if (request.method === 'DELETE') {
268
+ const result = await registrar.revokeApp(companySecret, appName);
269
+ if (!result.ok)
270
+ return errorResponse(result.reason, result.retryAfterMs);
271
+ return okResponse({ revoked: result.revoked });
272
+ }
273
+ }
274
+ catch (error) {
275
+ // Name and code only: a driver error's message can quote the query and
276
+ // its parameters, and a parameter may be (a hash of) a secret.
277
+ const name = error instanceof Error ? error.name : typeof error;
278
+ const code = error?.code;
279
+ console.error(`keys registrar: ${request.method} failed (${name}${typeof code === 'string' ? ` ${code}` : ''})`);
280
+ return unavailableResponse();
281
+ }
282
+ return plainResponse(405);
283
+ };
284
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `runRotationSweep` (docs/contracts.md C3): the sweep a host runs from its
3
+ * migrate container after `rotate-host.mjs start`. It moves every wrapped key
4
+ * onto the new wrap key id and every signed row onto the new signing
5
+ * generation, then counts what is left and reports it. `promote` reads that
6
+ * report.
7
+ *
8
+ * The counts come from the stored labels, not from the ids the sweep was told
9
+ * about, so a version left under an id nobody named still shows up.
10
+ */
11
+ import { type HeldKeys } from '../held/index.js';
12
+ import type { SigningGenerationMigrator } from '../issued/resign.js';
13
+ export interface RotationSweepOptions {
14
+ readonly hostId: string;
15
+ readonly kekIdNew: string;
16
+ readonly sigIdNew: string;
17
+ /** Built with an operator database handle and a credential holding `rewrap`. Leave out for a host that holds no wrapped keys. */
18
+ readonly held?: Pick<HeldKeys, 'rewrap' | 'countNotUnder' | 'kekIdsInUse'>;
19
+ /** Built with a credential holding `resign`. Leave out for a host that signs nothing, such as an `app-*` host. */
20
+ readonly migrator?: Pick<SigningGenerationMigrator, 'resignBatch' | 'countNotGeneration' | 'generationsInUse'>;
21
+ /** The public key of `sigIdNew`. Required with `migrator`. */
22
+ readonly targetPublicKey?: Uint8Array;
23
+ /** Unix milliseconds. Defaults to `Date.now`. */
24
+ readonly now?: () => number;
25
+ }
26
+ /** What `promote --report` reads. */
27
+ export interface RotationSweepReport {
28
+ readonly version: 1;
29
+ readonly hostId: string;
30
+ readonly kekIdNew: string;
31
+ readonly sigIdNew: string;
32
+ readonly rewrapped: number;
33
+ readonly resigned: number;
34
+ readonly remainingWrapped: number;
35
+ readonly remainingSigned: number;
36
+ /** Whether the held-key sweep ran (`held` was given). When false, `remainingWrapped` is 0 because nothing was counted. */
37
+ readonly heldSwept: boolean;
38
+ /** Whether the signing sweep ran (`migrator` was given). When false, `remainingSigned` is 0 because nothing was counted. */
39
+ readonly signedSwept: boolean;
40
+ /** Unix milliseconds. */
41
+ readonly finishedAt: number;
42
+ }
43
+ export type RotationSweepResult = {
44
+ readonly ok: true;
45
+ readonly report: RotationSweepReport;
46
+ } | {
47
+ readonly ok: false;
48
+ readonly step: 'rewrap' | 'resign' | 'input';
49
+ readonly reason: string;
50
+ /** The key id or generation being moved when it stopped. */
51
+ readonly from?: string;
52
+ /** Moved before it stopped. Nothing here is a report: do not promote. */
53
+ readonly rewrapped: number;
54
+ readonly resigned: number;
55
+ };
56
+ export declare function runRotationSweep(options: RotationSweepOptions): Promise<RotationSweepResult>;
@@ -0,0 +1,89 @@
1
+ /**
2
+ * `runRotationSweep` (docs/contracts.md C3): the sweep a host runs from its
3
+ * migrate container after `rotate-host.mjs start`. It moves every wrapped key
4
+ * onto the new wrap key id and every signed row onto the new signing
5
+ * generation, then counts what is left and reports it. `promote` reads that
6
+ * report.
7
+ *
8
+ * The counts come from the stored labels, not from the ids the sweep was told
9
+ * about, so a version left under an id nobody named still shows up.
10
+ */
11
+ import { HeldKeysError } from '../held/index.js';
12
+ import { ID_PATTERN } from '../worker-contract.js';
13
+ const RESIGN_BATCH_SIZE = 100;
14
+ export async function runRotationSweep(options) {
15
+ const { hostId, kekIdNew, sigIdNew, held, migrator, targetPublicKey } = options;
16
+ const now = options.now ?? Date.now;
17
+ let rewrapped = 0;
18
+ let resigned = 0;
19
+ const stop = (step, reason, from) => ({
20
+ ok: false,
21
+ step,
22
+ reason,
23
+ ...(from === undefined ? {} : { from }),
24
+ rewrapped,
25
+ resigned,
26
+ });
27
+ for (const id of [hostId, kekIdNew, sigIdNew]) {
28
+ if (!ID_PATTERN.test(id))
29
+ return stop('input', 'bad_request');
30
+ }
31
+ if (migrator && !(targetPublicKey instanceof Uint8Array && targetPublicKey.byteLength === 32)) {
32
+ return stop('input', 'bad_request');
33
+ }
34
+ if (held) {
35
+ for (const kekIdOld of await held.kekIdsInUse()) {
36
+ if (kekIdOld === kekIdNew)
37
+ continue;
38
+ try {
39
+ rewrapped += (await held.rewrap({ kekIdOld, kekIdNew })).rewrapped;
40
+ }
41
+ catch (error) {
42
+ if (error instanceof HeldKeysError)
43
+ return stop('rewrap', error.code, kekIdOld);
44
+ throw error;
45
+ }
46
+ }
47
+ }
48
+ if (migrator && targetPublicKey) {
49
+ for (const fromGenerationId of await migrator.generationsInUse()) {
50
+ if (fromGenerationId === sigIdNew)
51
+ continue;
52
+ let cursor = null;
53
+ for (;;) {
54
+ const batch = await migrator.resignBatch({
55
+ fromGenerationId,
56
+ toGenerationId: sigIdNew,
57
+ targetPublicKey,
58
+ cursor,
59
+ limit: RESIGN_BATCH_SIZE,
60
+ });
61
+ resigned += batch.migratedIds.length;
62
+ if (!batch.ok) {
63
+ return stop('resign', batch.reason, fromGenerationId);
64
+ }
65
+ if (batch.complete)
66
+ break;
67
+ cursor = batch.resumeCursor;
68
+ }
69
+ }
70
+ }
71
+ const remainingWrapped = held ? await held.countNotUnder(kekIdNew) : 0;
72
+ const remainingSigned = migrator ? await migrator.countNotGeneration(sigIdNew) : 0;
73
+ return {
74
+ ok: true,
75
+ report: {
76
+ version: 1,
77
+ hostId,
78
+ kekIdNew,
79
+ sigIdNew,
80
+ rewrapped,
81
+ resigned,
82
+ remainingWrapped,
83
+ remainingSigned,
84
+ heldSwept: held !== undefined,
85
+ signedSwept: migrator !== undefined,
86
+ finishedAt: now(),
87
+ },
88
+ };
89
+ }
@@ -28,6 +28,10 @@ import { type SignableRow, type SignedKind } from '../worker-contract.js';
28
28
  * `Object.keys(obj).sort()` alone gives JCS's key order.
29
29
  */
30
30
  export declare function canonicalJson(value: unknown): string;
31
+ /** True when the string holds a UTF-16 surrogate that is not half of a valid pair. */
32
+ export declare function hasLoneSurrogate(value: string): boolean;
33
+ /** True when a string, or an object key, anywhere in the JSON-like value holds a lone surrogate. */
34
+ export declare function containsLoneSurrogate(value: unknown): boolean;
31
35
  /**
32
36
  * `wtfalch-keys:${kind}:v1\n` + `canonicalJson(value)`, as UTF-8 bytes.
33
37
  *
@@ -33,6 +33,22 @@ import { ID_PATTERN, SIGNED_PREFIX, } from '../worker-contract.js';
33
33
  export function canonicalJson(value) {
34
34
  return encodeValue(value);
35
35
  }
36
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
37
+ /** True when the string holds a UTF-16 surrogate that is not half of a valid pair. */
38
+ export function hasLoneSurrogate(value) {
39
+ return LONE_SURROGATE.test(value);
40
+ }
41
+ /** True when a string, or an object key, anywhere in the JSON-like value holds a lone surrogate. */
42
+ export function containsLoneSurrogate(value) {
43
+ if (typeof value === 'string')
44
+ return hasLoneSurrogate(value);
45
+ if (Array.isArray(value))
46
+ return value.some(containsLoneSurrogate);
47
+ if (value !== null && typeof value === 'object') {
48
+ return Object.entries(value).some(([k, v]) => hasLoneSurrogate(k) || containsLoneSurrogate(v));
49
+ }
50
+ return false;
51
+ }
36
52
  function encodeValue(value) {
37
53
  if (value === null)
38
54
  return 'null';
@@ -95,6 +111,12 @@ function encodeString(value) {
95
111
  * other's.
96
112
  */
97
113
  export function encodeSigned(kind, value) {
114
+ // A lone surrogate has no UTF-8 form, and RFC 8785 forbids it. Without this,
115
+ // JSON.stringify would sign its \udXXX escape, a second spelling of a row
116
+ // that a strict encoder would refuse or write as U+FFFD.
117
+ if (containsLoneSurrogate(value)) {
118
+ throw new TypeError('encodeSigned: a string holding a lone surrogate is refused');
119
+ }
98
120
  const header = `${SIGNED_PREFIX}${kind}:v1\n`;
99
121
  return new TextEncoder().encode(header + canonicalJson(value));
100
122
  }