@mdbase-dev/sdk 0.2.98 → 0.2.99

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.
@@ -44,6 +44,12 @@ export interface AppInstallationTimerChannel {
44
44
  readonly channelId: string | null;
45
45
  readonly pending: "register" | "delete" | null;
46
46
  }
47
+ export interface ScopedInstallationReference {
48
+ readonly accountId: string;
49
+ readonly collectionId: string;
50
+ readonly reference: string;
51
+ }
52
+ export type ScopedInstallationPaired = (reference: ScopedInstallationReference) => boolean;
47
53
  export interface AppInstallationSignInOptions extends AppInstallationStoreOptions {
48
54
  /** Expected registered display name, compared exactly with CP responses. */
49
55
  readonly appName: string;
@@ -161,7 +167,12 @@ export interface AppInstallationSignInView {
161
167
  export interface AppInstallationStartOptions {
162
168
  readonly collectionHint?: string | null;
163
169
  }
164
- export declare let replaceRefusedAppInstallation: (flow: AppProtectedInstallationSignIn, stop: () => Promise<void>) => Promise<void>;
170
+ export declare let replaceRefusedAppInstallation: (flow: AppProtectedInstallationSignIn, stop: () => Promise<void>, childPaired?: ScopedInstallationPaired) => Promise<void>;
171
+ export declare let installationRecovery: {
172
+ replacementPending(flow: AppProtectedInstallationSignIn): boolean;
173
+ references(flow: AppProtectedInstallationSignIn): readonly ScopedInstallationReference[];
174
+ replaceRetained(flow: AppProtectedInstallationSignIn, installation: AppInstallationCustodyAuthority, collection: string, expected: string): Promise<string | null>;
175
+ };
165
176
  export declare class AppProtectedInstallationSignIn {
166
177
  private readonly store;
167
178
  private state;
@@ -197,10 +208,9 @@ export declare class AppProtectedInstallationSignIn {
197
208
  /** Original operation+secret already committed before this FIRST HTTP. An
198
209
  * explicit repeat uses the same request, never a new installation/device. */
199
210
  start(options?: AppInstallationStartOptions): Promise<AppInstallationSignInView>;
200
- /** Replace the protected identity in place under the sign-in ledger lease.
201
- * The old replica and custody stores remain under the original IDs.
202
- */
211
+ /** Replace the protected identity under the same sign-in ledger lease. */
203
212
  private replaceRefusedInstallation;
213
+ private replacementPending;
204
214
  /** Explicit user retry after an exact typed expiry. Renew ONLY the pairing
205
215
  * window; installation/device/account/challenge/keys/proof remain original.
206
216
  * Persist the new request and its parent capability BEFORE HTTP. Unknown
@@ -265,11 +275,15 @@ export declare class AppProtectedInstallationSignIn {
265
275
  /** Protected references to retired scopes. Each non-null value identifies a
266
276
  * separate original installation ledger, never a replacement credential. */
267
277
  collectionRecoveries(): Readonly<Record<string, string | null>>;
278
+ private scopedInstallationReferences;
279
+ private retainedRecoveriesForAccount;
280
+ private replaceRetainedCollectionInstallation;
268
281
  retireCollectionScope(installation: AppInstallationCustodyAuthority, collection: string, expectedReplacement?: string | null): Promise<void>;
269
282
  /** Only an explicit recovery gesture creates this new slot reference. The
270
283
  * new slot performs ordinary account confirmation, attestation and approval. */
271
284
  freshCollectionInstallation(installation: AppInstallationCustodyAuthority, collection: string): Promise<string>;
272
285
  private saveRecovery;
286
+ private saveWithRecoveryMetadata;
273
287
  /** Ask, from a fresh user gesture, for declared optional file actions on one
274
288
  * approved collection, with a one-line reason shown by Connect. A scope-only
275
289
  * re-consent under a new in-memory secret: nothing is persisted, so a lost
@@ -10,6 +10,7 @@ import { isAppEnvironmentSelection } from "./app-environment.js";
10
10
  import { AppInstallationStore, AppInstallationStorageError } from "./installation-store.js";
11
11
  import { isAppInstallationId } from "./owner.js";
12
12
  import { appServerOutcome, appServerProblem } from "./cp-problem.js";
13
+ import { eraseInstallationStores } from "./sign-out-erase.js";
13
14
  export class AppInstallationSignInError extends Error {
14
15
  reason;
15
16
  server;
@@ -135,6 +136,7 @@ function collectionListing(value) {
135
136
  return Object.freeze({ collectionId, displayName: r.display_name, role: r.role, ...(availability ? { availability } : {}), ...(allowed ? { fileActions: allowed } : {}), ...(r.mode === "private" ? { mode: "private" } : {}) });
136
137
  }));
137
138
  }
139
+ const MAX_SCOPED_INSTALLATIONS = 1000;
138
140
  const FILE_ACTIONS = ["list", "read", "add", "replace", "move", "delete"];
139
141
  function fileActions(v, allowed = FILE_ACTIONS, empty = true) {
140
142
  if (!Array.isArray(v) || v.length > FILE_ACTIONS.length || (!empty && !v.length) || new Set(v).size !== v.length || v.some(a => !allowed.includes(a)))
@@ -153,11 +155,19 @@ function verificationUri(value, base, hint) {
153
155
  return value === base || (hint !== null && value === `${base}?collection_hint=${hint}`) ? value : null;
154
156
  }
155
157
  export let replaceRefusedAppInstallation;
158
+ export let installationRecovery;
156
159
  export class AppProtectedInstallationSignIn {
157
160
  store;
158
161
  state;
159
162
  options;
160
- static { replaceRefusedAppInstallation = (flow, stop) => flow.replaceRefusedInstallation(stop); }
163
+ static {
164
+ replaceRefusedAppInstallation = (flow, stop, childPaired) => flow.replaceRefusedInstallation(stop, childPaired);
165
+ installationRecovery = {
166
+ replacementPending: flow => flow.replacementPending(),
167
+ references: flow => flow.scopedInstallationReferences(),
168
+ replaceRetained: (flow, installation, collection, expected) => flow.replaceRetainedCollectionInstallation(installation, collection, expected),
169
+ };
170
+ }
161
171
  closed = false;
162
172
  busy = false;
163
173
  nativeAcknowledged = false;
@@ -246,7 +256,7 @@ export class AppProtectedInstallationSignIn {
246
256
  const fields = `${base},requestedCreateCollections,collectionIds,createCollections,consentRequest`;
247
257
  const r = legacy ? { ...object(parsed, base), version: 3, renewal: null, requestedCreateCollections: false, collectionIds: [], createCollections: false, consentRequest: null }
248
258
  : parsed?.version === 2 ? { ...object(parsed, fields), version: 3, renewal: null }
249
- : object(parsed, `${fields},renewal${Object.hasOwn(parsed, "collectionSelection") ? ",collectionSelection" : ""}${Object.hasOwn(parsed, "timerConsent") ? ",timerConsent" : ""}${Object.hasOwn(parsed, "timerChannel") ? ",timerChannel" : ""}${Object.hasOwn(parsed, "owner") ? ",owner" : ""}${Object.hasOwn(parsed, "collectionListing") ? ",collectionListing" : ""}${Object.hasOwn(parsed, "collectionRecoveries") ? ",collectionRecoveries" : ""}${Object.hasOwn(parsed, "recoveryFor") ? ",recoveryFor" : ""}${Object.hasOwn(parsed, "nativeAuthorization") ? ",nativeAuthorization" : ""}${Object.hasOwn(parsed, "nativeSelection") ? ",nativeSelection" : ""}${Object.hasOwn(parsed, "nativeGrants") ? ",nativeGrants" : ""}${Object.hasOwn(parsed, "requestedPrivateDevice") ? ",requestedPrivateDevice" : ""}${Object.hasOwn(parsed, "privateDeviceCollectionIds") ? ",privateDeviceCollectionIds" : ""}${Object.hasOwn(parsed, "requestSent") ? ",requestSent" : ""}`);
259
+ : object(parsed, `${fields},renewal${Object.hasOwn(parsed, "collectionSelection") ? ",collectionSelection" : ""}${Object.hasOwn(parsed, "timerConsent") ? ",timerConsent" : ""}${Object.hasOwn(parsed, "timerChannel") ? ",timerChannel" : ""}${Object.hasOwn(parsed, "owner") ? ",owner" : ""}${Object.hasOwn(parsed, "collectionListing") ? ",collectionListing" : ""}${Object.hasOwn(parsed, "collectionRecoveries") ? ",collectionRecoveries" : ""}${Object.hasOwn(parsed, "retainedCollectionRecoveries") ? ",retainedCollectionRecoveries" : ""}${Object.hasOwn(parsed, "replacementPending") ? ",replacementPending" : ""}${Object.hasOwn(parsed, "recoveryFor") ? ",recoveryFor" : ""}${Object.hasOwn(parsed, "nativeAuthorization") ? ",nativeAuthorization" : ""}${Object.hasOwn(parsed, "nativeSelection") ? ",nativeSelection" : ""}${Object.hasOwn(parsed, "nativeGrants") ? ",nativeGrants" : ""}${Object.hasOwn(parsed, "requestedPrivateDevice") ? ",requestedPrivateDevice" : ""}${Object.hasOwn(parsed, "privateDeviceCollectionIds") ? ",privateDeviceCollectionIds" : ""}${Object.hasOwn(parsed, "requestSent") ? ",requestSent" : ""}`);
250
260
  if (r.version !== 3 || r.appId !== p.appId || r.owner !== p.owner || r.kind !== (p.installationKind ?? "app-runtime") || r.origin !== p.origin || r.cpOrigin !== p.cpOrigin || r.environment !== p.environment || typeof r.confirmed !== "boolean" || typeof r.nativeStarted !== "boolean")
251
261
  throw fail("recovery_required");
252
262
  const s = r;
@@ -355,8 +365,34 @@ export class AppProtectedInstallationSignIn {
355
365
  if (!s.token || !s.confirmed || !s.selection || !s.proof || !s.collectionRecoveries || typeof s.collectionRecoveries !== "object" || Array.isArray(s.collectionRecoveries))
356
366
  throw fail("recovery_required");
357
367
  const entries = Object.entries(s.collectionRecoveries);
358
- if (entries.length > 1000 || entries.some(([collection, replacement]) => !(s.collectionIds.includes(id(collection)) || s.nativeGrants?.some(c => c.collection_id === collection)) || (replacement !== null && !id(replacement))))
368
+ if (entries.length > MAX_SCOPED_INSTALLATIONS || entries.some(([collection, replacement]) => !(s.collectionIds.includes(id(collection)) || s.nativeGrants?.some(c => c.collection_id === collection)) || (replacement !== null && !id(replacement))))
369
+ throw fail("recovery_required");
370
+ }
371
+ if (s.replacementPending !== undefined && (s.replacementPending !== true || !s.token || !s.confirmed))
372
+ throw fail("recovery_required");
373
+ if (s.retainedCollectionRecoveries !== undefined) {
374
+ const retained = s.retainedCollectionRecoveries;
375
+ if (s.recoveryFor || !retained || typeof retained !== "object" || Array.isArray(retained))
376
+ throw fail("recovery_required");
377
+ const references = Object.values(s.collectionRecoveries ?? {}).filter(reference => reference !== null);
378
+ const seen = new Set(references);
379
+ if (seen.size !== references.length)
359
380
  throw fail("recovery_required");
381
+ for (const [account, collections] of Object.entries(retained)) {
382
+ id(account);
383
+ if (!collections || typeof collections !== "object" || Array.isArray(collections))
384
+ throw fail("recovery_required");
385
+ const entries = Object.entries(collections);
386
+ if (!entries.length || seen.size + entries.length > MAX_SCOPED_INSTALLATIONS)
387
+ throw fail("recovery_required");
388
+ for (const [collection, reference] of entries) {
389
+ id(collection);
390
+ id(reference);
391
+ if (seen.has(reference) || (account === s.selection?.accountId && Object.hasOwn(s.collectionRecoveries ?? {}, collection)))
392
+ throw fail("recovery_required");
393
+ seen.add(reference);
394
+ }
395
+ }
360
396
  }
361
397
  if (s.nativeAuthorization) {
362
398
  const a = object(s.nativeAuthorization, "requestId,authorizationId,applicationId,manifestDigest");
@@ -543,21 +579,40 @@ export class AppProtectedInstallationSignIn {
543
579
  }
544
580
  return this.exclusive(() => this.startRequest(hint));
545
581
  }
546
- /** Replace the protected identity in place under the sign-in ledger lease.
547
- * The old replica and custody stores remain under the original IDs.
548
- */
549
- replaceRefusedInstallation(stop) {
582
+ /** Replace the protected identity under the same sign-in ledger lease. */
583
+ replaceRefusedInstallation(stop, childPaired) {
550
584
  return this.exclusive(async () => {
551
- if (!this.credentialRefused || !this.state.token ||
552
- Object.values(this.state.collectionRecoveries ?? {}).some(reference => reference !== null))
585
+ const state = this.state;
586
+ if (!(this.credentialRefused || state.replacementPending) || !state.token)
587
+ throw fail("recovery_required");
588
+ const scoped = this.scopedInstallationReferences();
589
+ if (scoped.some(reference => !childPaired?.(reference)))
553
590
  throw fail("recovery_required");
591
+ const selected = this.confirmedSelection();
592
+ const collectionIds = [...state.collectionIds, ...(state.nativeGrants ?? []).map(grant => grant.collection_id)];
593
+ if (!state.replacementPending) {
594
+ // Keep the scope on disk until erasure succeeds, including across reloads.
595
+ await this.saveWithRecoveryMetadata({ ...state, replacementPending: true });
596
+ }
554
597
  await stop();
555
- await this.save(AppProtectedInstallationSignIn.freshState(this.options));
598
+ if (!await eraseInstallationStores({ ...selected, collectionIds }))
599
+ throw fail("recovery_required");
600
+ if (scoped.some(reference => !childPaired?.(reference)))
601
+ throw fail("recovery_required");
602
+ const fresh = AppProtectedInstallationSignIn.freshState(this.options);
603
+ if (scoped.length) {
604
+ const retained = {};
605
+ for (const { accountId, collectionId, reference } of scoped)
606
+ (retained[accountId] ??= {})[collectionId] = reference;
607
+ fresh.retainedCollectionRecoveries = retained;
608
+ }
609
+ await this.save(fresh);
556
610
  this.credentialRefused = false;
557
611
  this.nativeAcknowledged = false;
558
612
  this.closedPairing = null;
559
613
  });
560
614
  }
615
+ replacementPending() { this.check(); return this.state.replacementPending === true; }
561
616
  /** Explicit user retry after an exact typed expiry. Renew ONLY the pairing
562
617
  * window; installation/device/account/challenge/keys/proof remain original.
563
618
  * Persist the new request and its parent capability BEFORE HTTP. Unknown
@@ -1075,7 +1130,45 @@ export class AppProtectedInstallationSignIn {
1075
1130
  * separate original installation ledger, never a replacement credential. */
1076
1131
  collectionRecoveries() {
1077
1132
  this.check();
1078
- return Object.freeze({ ...this.state.collectionRecoveries });
1133
+ return Object.freeze({ ...this.retainedRecoveriesForAccount(), ...this.state.collectionRecoveries });
1134
+ }
1135
+ scopedInstallationReferences() {
1136
+ this.check();
1137
+ const refs = [];
1138
+ for (const [accountId, collections] of Object.entries(this.state.retainedCollectionRecoveries ?? {})) {
1139
+ for (const [collectionId, reference] of Object.entries(collections))
1140
+ refs.push({ accountId, collectionId, reference });
1141
+ }
1142
+ const accountId = this.state.selection?.accountId;
1143
+ if (accountId)
1144
+ for (const [collectionId, reference] of Object.entries(this.state.collectionRecoveries ?? {})) {
1145
+ if (reference !== null)
1146
+ refs.push({ accountId, collectionId, reference });
1147
+ }
1148
+ return refs;
1149
+ }
1150
+ retainedRecoveriesForAccount() {
1151
+ const { token, selection, retainedCollectionRecoveries } = this.state;
1152
+ return token && selection ? retainedCollectionRecoveries?.[selection.accountId] : undefined;
1153
+ }
1154
+ replaceRetainedCollectionInstallation(installation, collection, expected) {
1155
+ const check = this.consentGuard(installation);
1156
+ return this.exclusive(async () => {
1157
+ check();
1158
+ id(collection);
1159
+ id(expected);
1160
+ const retained = this.retainedRecoveriesForAccount();
1161
+ if (!retained?.[collection])
1162
+ return null;
1163
+ if (retained[collection] !== expected)
1164
+ throw fail("fenced");
1165
+ const reference = crypto.randomUUID();
1166
+ await this.saveWithRecoveryMetadata({ ...this.state, retainedCollectionRecoveries: {
1167
+ ...this.state.retainedCollectionRecoveries, [installation.scope.account]: { ...retained, [collection]: reference },
1168
+ } });
1169
+ check();
1170
+ return reference;
1171
+ });
1079
1172
  }
1080
1173
  retireCollectionScope(installation, collection, expectedReplacement = null) {
1081
1174
  const check = this.consentGuard(installation);
@@ -1107,14 +1200,18 @@ export class AppProtectedInstallationSignIn {
1107
1200
  const existing = this.state.collectionRecoveries[collection];
1108
1201
  if (existing !== null)
1109
1202
  return existing; // pending/unknown retries keep the SAME fresh slot
1203
+ if (this.scopedInstallationReferences().length >= MAX_SCOPED_INSTALLATIONS)
1204
+ throw fail("recovery_required");
1110
1205
  const replacement = crypto.randomUUID();
1111
1206
  await this.saveRecovery(collection, replacement);
1112
1207
  check();
1113
1208
  return replacement;
1114
1209
  });
1115
1210
  }
1116
- async saveRecovery(collection, replacement) {
1117
- const state = { ...this.state, collectionRecoveries: { ...this.state.collectionRecoveries, [collection]: replacement } };
1211
+ saveRecovery(collection, replacement) {
1212
+ return this.saveWithRecoveryMetadata({ ...this.state, collectionRecoveries: { ...this.state.collectionRecoveries, [collection]: replacement } });
1213
+ }
1214
+ async saveWithRecoveryMetadata(state) {
1118
1215
  // Recovery metadata shares the original ledger bound; discard only display
1119
1216
  // cache if necessary, never the original receipt or unrelated scope state.
1120
1217
  if (new TextEncoder().encode(JSON.stringify(state)).length > 128 * 1024)