@tinycloud/web-sdk 3.14.0-beta.9 → 3.16.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.
@@ -0,0 +1,23 @@
1
+ /*!
2
+ * The buffer module from node.js, for the browser.
3
+ *
4
+ * @author Feross Aboukhadijeh <https://feross.org>
5
+ * @license MIT
6
+ */
7
+
8
+ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
9
+
10
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
11
+
12
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13
+
14
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
15
+
16
+ /**
17
+ * [js-sha3]{@link https://github.com/emn178/js-sha3}
18
+ *
19
+ * @version 0.8.0
20
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
21
+ * @copyright Chen, Yi-Cyuan 2015-2018
22
+ * @license MIT
23
+ */
@@ -1,6 +1,7 @@
1
- import { type IDataVaultService, type ISecretsService, type Manifest, type PermissionEntry, type Result, type SecretScopeOptions, type SecretPutOptions } from "@tinycloud/sdk-core";
1
+ import { type IDataVaultService, type ISecretsService, type Manifest, type PermissionEntry, type Result, type SecretGetOptions, type SecretScopeOptions, type SecretPutOptions } from "@tinycloud/sdk-core";
2
2
  import type { VaultError } from "@tinycloud/sdk-core";
3
- type RequestPermissions = (additional: PermissionEntry[]) => Promise<{
3
+ import type { RequestPermissionsOptions } from "./requestPermissionsCore";
4
+ type RequestPermissions = (additional: PermissionEntry[], options?: RequestPermissionsOptions) => Promise<{
4
5
  approved: boolean;
5
6
  delegations?: readonly unknown[];
6
7
  }>;
@@ -9,6 +10,10 @@ export interface WebSecretsServiceConfig {
9
10
  space?: string;
10
11
  getManifest: () => Manifest | Manifest[] | undefined;
11
12
  requestPermissions: RequestPermissions;
13
+ /** The encryption network of this secrets space; an opted-in read asks only for a key on it. */
14
+ getEncryptionNetworkId?: () => string | undefined;
15
+ /** Whether the node has named keys. `put` is refused before any prompt when it does not (`false`) and when it cannot be checked (`undefined`). */
16
+ namedKeysSupported?: () => boolean | undefined | Promise<boolean | undefined>;
12
17
  resolveSpace?: (space: string) => string;
13
18
  getUnlockSigner?: () => unknown;
14
19
  }
@@ -22,14 +27,24 @@ export declare class WebSecretsService implements ISecretsService {
22
27
  get isUnlocked(): boolean;
23
28
  unlock(signer?: unknown): Promise<Result<void, VaultError>>;
24
29
  lock(): void;
25
- get(name: string, options?: SecretScopeOptions): ReturnType<ISecretsService["get"]>;
26
- getEntry(name: string, options?: SecretScopeOptions): ReturnType<ISecretsService["getEntry"]>;
30
+ /** With `requestPermission: true`, a read missing its own key's decrypt asks for exactly that key once, then reads again. */
31
+ get(name: string, options?: SecretGetOptions): ReturnType<ISecretsService["get"]>;
32
+ /** As {@link get}. */
33
+ getEntry(name: string, options?: SecretGetOptions): ReturnType<ISecretsService["getEntry"]>;
34
+ /**
35
+ * The ask goes through this page's permission prompt, never the node's own
36
+ * escalation, so the node reads without `requestPermission`. A declined or
37
+ * failed ask is PERMISSION_DENIED, as for a put; nothing is remembered, so
38
+ * the next opted-in read asks again.
39
+ */
40
+ private read;
27
41
  put(name: string, value: string, options?: SecretPutOptions): ReturnType<ISecretsService["put"]>;
28
42
  delete(name: string, options?: SecretScopeOptions): ReturnType<ISecretsService["delete"]>;
29
43
  list(options?: SecretScopeOptions): ReturnType<ISecretsService["list"]>;
30
44
  listAll(): ReturnType<ISecretsService["listAll"]>;
31
45
  private get service();
32
46
  private ensureMutationPermission;
47
+ private ask;
33
48
  private restoreUnlockAfterEscalation;
34
49
  private hasMutationPermission;
35
50
  }
@@ -24,13 +24,15 @@ export interface RequestPermissionsCoreDeps {
24
24
  appName: string;
25
25
  appIcon?: string;
26
26
  additional: PermissionEntry[];
27
+ expiryMs?: number;
28
+ caption?: string;
27
29
  onBehalfOf?: string;
28
30
  allowSuppression?: boolean;
29
31
  }) => Promise<{
30
32
  approved: boolean;
31
33
  suppressPromptFor30Days?: boolean;
32
34
  }>;
33
- /** True when the signer shows the request itself (OpenKey): the SDK prompt is skipped and no opt-out is read or stored. */
35
+ /** True when OpenKey signs and shows its own approval: the SDK prompt is skipped and no opt-out is read or stored. */
34
36
  skipPrompt?: boolean;
35
37
  /** Whether this page/app has opted out of the SDK explainer prompt. */
36
38
  isPromptSuppressed?: () => boolean;
@@ -57,6 +59,13 @@ export interface RequestPermissionsOptions {
57
59
  * the prompt offers none, and none is stored. Default `true`.
58
60
  */
59
61
  allowPromptSuppression?: boolean;
62
+ /**
63
+ * The app's own short label for what this request is for, e.g. `"TrustBot's chat history"`. The prompt shows it as
64
+ * plain text, attributed to the app, beneath the line it derives from the request (the exact resource, each action
65
+ * and the expiry). It never replaces that line. Whitespace is folded and it is cut to 120 characters. A signer that
66
+ * shows the request itself (OpenKey) does not show it.
67
+ */
68
+ caption?: string;
60
69
  }
61
70
  /**
62
71
  * Validate the additional permissions array and throw with a clear
@@ -25,8 +25,18 @@ export declare function isPanelResourceSet(resources: readonly Resource[], owner
25
25
  /** True when `grant` is exactly a panel grant of the session owned by `address`. */
26
26
  export declare function isPanelGrant(grant: PortableDelegation, address: string): boolean;
27
27
  /**
28
- * Stores the panel's own grants among `grants` for `address`, replacing a stored grant with the same cid. Other
29
- * delegations (an app's larger grant that already covered the request) are never stored.
28
+ * Matches exact secret keys on the owner's default network, or the reserved bot-history
29
+ * key by itself. Only decrypt and/or key.create, and no caveats.
30
+ */
31
+ export declare function isSecretKeyResourceSet(resources: readonly Resource[], owner: {
32
+ readonly address: string;
33
+ readonly chainId: number;
34
+ }): boolean;
35
+ /** True when `grant` is exactly a grant of the session owner's own secrets' keys (see `isSecretKeyResourceSet`). */
36
+ export declare function isSecretKeyGrant(grant: PortableDelegation, address: string): boolean;
37
+ /**
38
+ * Stores the panel's own grants and the owner's secret-key grants among `grants` for `address`, replacing a stored
39
+ * grant with the same cid. Other delegations (an app's larger grant that already covered the request) are never stored.
30
40
  */
31
41
  export declare function rememberRuntimeGrants(store: RuntimeGrantStore, address: string, grants: readonly PortableDelegation[], isCurrent?: () => boolean): Promise<void>;
32
42
  /**
@@ -39,5 +49,35 @@ export declare function reuseRuntimeGrants(store: RuntimeGrantStore, address: st
39
49
  readonly budgetMs?: number;
40
50
  readonly isCurrent?: () => boolean;
41
51
  }): Promise<void>;
52
+ /** A stored grant. `askedBy` names the apps it was approved for (the `onBehalfOf` of each approving request). */
53
+ export type StoredRuntimeGrant = PortableDelegation & {
54
+ readonly askedBy?: readonly string[];
55
+ };
56
+ /** The apps a stored grant was approved for; anything else in the field is ignored. */
57
+ export declare function storedGrantAskers(grant: PortableDelegation): readonly string[];
58
+ /**
59
+ * True when a grant entry is elevated: any service this module does not know (decrypt and key creation among them),
60
+ * anything in the secrets space, or a caveat of any shape. Failing closed: an entry this function cannot classify is
61
+ * elevated, and an elevated grant is never written to storage.
62
+ */
63
+ export declare function isElevatedResource(resource: {
64
+ readonly service: string;
65
+ readonly space?: string | undefined;
66
+ readonly caveats?: unknown;
67
+ }): boolean;
68
+ /** True when every resource is in a space the owner owns and none is elevated. An empty set is not rememberable. */
69
+ export declare function isRememberableResourceSet(resources: readonly Resource[], owner: {
70
+ readonly address: string;
71
+ readonly chainId: number;
72
+ }): boolean;
73
+ /** True when `grant` is an unexpired, non-elevated grant of the session owned by `address`. */
74
+ export declare function isRememberableGrant(grant: PortableDelegation, address: string): boolean;
75
+ /**
76
+ * Stores the non-elevated grants among `grants` for `address`, with `asker` added to the apps each was approved for,
77
+ * replacing a stored grant with the same cid. An elevated grant is never stored. A signed grant that spans several
78
+ * spaces arrives as several delegations with one cid; it is not stored, because a restore rebuilds its resources from
79
+ * the signed bytes, not from the delegation. A stored grant keeps its own signed expiry.
80
+ */
81
+ export declare function rememberAskedGrants(store: RuntimeGrantStore, address: string, grants: readonly PortableDelegation[], asker: string | undefined, isCurrent?: () => boolean): Promise<void>;
42
82
  export {};
43
83
  //# sourceMappingURL=runtimeGrantPersistence.d.ts.map
@@ -12,7 +12,8 @@
12
12
  import { TinyCloudNode, TinyCloudNodeConfig, type OpenKeyAuthorizeTinyCloud, type BootstrapWarning, type DelegateToOptions, type DelegateToResult, type ISessionStorage, type SignStrategy, type ValidatedRuntimeDelegation, type UnifiedOwnerRootInput, type UnifiedOwnerRootReceipt, type RegisterPolicyV3Input, type RegisterPolicyV3Receipt } from "@tinycloud/node-sdk/core";
13
13
  import type { NodeSignOutStatus } from "@tinycloud/node-sdk";
14
14
  import { type LocalCopyPurgeFailedEvent } from "./replica-wiring";
15
- import { IKVService, ISQLService, IDuckDbService, IDataVaultService, ISecretsService, ISpaceService, ISpace, ISharingService, ICapabilityKeyRegistry, IHooksService, IEncryptionService, DelegationManager, Delegation, DelegationRevocationReceipt, Result, DelegationError, ClientSession, Extension, type TelemetryConfig, type RetryPolicy, ISpaceCreationHandler, type Manifest, type ComposedManifestRequest, type AccountService, type ResolvedDelegate, type PermissionEntry, type NetworkDescriptor, type CreateOwnerDelegationParams, type OwnerDelegationReceipt, type LocalNodeIdentityStore, type OnNodeNotFound, type RegistrySequenceStore, SignInOptions, type RegistryCacheStore, type StorageFullEvent, type IStorageService } from "@tinycloud/sdk-core";
15
+ import { IKVService, ISQLService, IDuckDbService, IDataVaultService, ISecretsService, ISpaceService, ISpace, ISharingService, ICapabilityKeyRegistry, IHooksService, IEncryptionService, DelegationManager, Delegation, DelegationRevocationReceipt, Result, DelegationError, ClientSession, type ClientSignInResult, Extension, type TelemetryConfig, type RetryPolicy, ISpaceCreationHandler, type Manifest, type ComposedManifestRequest, type AccountService, type ResolvedDelegate, type PermissionEntry, type NetworkDescriptor, type CreateOwnerDelegationParams, type OwnerDelegationReceipt, type LocalNodeIdentityStore, type OnNodeNotFound, type RegistrySequenceStore, SignInOptions, type RegistryCacheStore, type StorageFullEvent, type IStorageService } from "@tinycloud/sdk-core";
16
+ import type { RegistryPublishOutcome } from "../registry-publish";
16
17
  import { type RequestPermissionsOptions } from "./requestPermissionsCore";
17
18
  import { type OpenKeySignPresentation } from "./openKeySignPresentation";
18
19
  import { type BrowserProvider, type BrowserWalletProvider } from "../adapters/browserProvider";
@@ -171,6 +172,12 @@ export interface Config extends ClientConfig {
171
172
  shareReceiver?: ShareReceiverServiceOptions;
172
173
  /** Floating button, panel, and toasts. `false` creates no host, button, toasts, or listeners. See {@link UiConfig}. */
173
174
  ui?: UiConfig | false;
175
+ /**
176
+ * Notified on every error from {@link TinyCloudWeb.ensureOwnerRegistryRecord} (verdict
177
+ * lookup, signer resolution, registry 4xx/5xx). Hosts can fold it into their own
178
+ * telemetry. The method's return value carries the outcome.
179
+ */
180
+ onRegistryPublishError?: (error: unknown) => void;
174
181
  }
175
182
  /**
176
183
  * Result of {@link TinyCloudWeb.requestPermissions}. On approve, `session`
@@ -442,8 +449,29 @@ export declare class TinyCloudWeb {
442
449
  * `maxExpiresAt` is forwarded only with it.
443
450
  */
444
451
  private openKeySignInOptions;
445
- signIn: (options?: SignInOptions) => Promise<ClientSession>;
452
+ signIn: (options?: SignInOptions) => Promise<ClientSignInResult>;
446
453
  private performSignIn;
454
+ /**
455
+ * Publish the owner's registry location record when the registry has none. The host app
456
+ * calls it, for example from TinyCloud One's `finish-setup=registry` link. The owner's
457
+ * wallet or OpenKey signature prompt is the consent: one signature, only when a record is
458
+ * missing.
459
+ *
460
+ * Only TinyCloud One and Home publish; elsewhere the SDK asks for no signature. On any
461
+ * other host, or when OpenKey refuses, an owner who has no
462
+ * record gets `"needs-one"`: send them to `AccountSetupRequiredError.setupUrl`
463
+ * (`https://tinycloud.one/?finish-setup=registry`) and have them sign in to the app
464
+ * again. A record is only ever created, never overwritten.
465
+ *
466
+ * On TinyCloud One or Home, the page that reads the `finish-setup=registry` intent must
467
+ * set `frame-ancestors 'self'` (or equivalent) so no outside origin can clickjack the
468
+ * tap, and must strip the query with `history.replaceState` after reading it so a reload
469
+ * or shared link does not keep reopening the prompt.
470
+ *
471
+ * Returns `"published"`, `"already-current"`, `"needs-one"` or `"unavailable"`.
472
+ * This method never throws.
473
+ */
474
+ ensureOwnerRegistryRecord(): Promise<RegistryPublishOutcome>;
447
475
  /**
448
476
  * Sign out: end the session on this instance and clear the persisted
449
477
  * session. Afterwards accessors return `undefined` and service calls remain
@@ -466,8 +494,23 @@ export declare class TinyCloudWeb {
466
494
  session: () => ClientSession | undefined;
467
495
  address: () => string | undefined;
468
496
  chainId: () => number | undefined;
469
- /** Returns whether the session or an unexpired runtime grant covers all entries. Never prompts. */
470
- hasPermissions(entries: PermissionEntry[]): boolean;
497
+ /**
498
+ * Returns whether the session or an unexpired runtime grant covers all entries. Never prompts. With
499
+ * `options.onBehalfOf`, only the session's own permissions and the grants approved for that app count; a grant
500
+ * approved for no app, or for another one, does not. Without it, every grant counts.
501
+ */
502
+ hasPermissions(entries: PermissionEntry[], options?: {
503
+ readonly onBehalfOf?: string;
504
+ }): boolean;
505
+ /** The apps each installed grant was approved for, by cid. Per node, so a new sign-in starts empty. */
506
+ private readonly grantAskers;
507
+ private grantAskersOf;
508
+ private grantCidsAskedBy;
509
+ /**
510
+ * Resolves once the grants kept from before a page reload are active again, or after at most four seconds. Never
511
+ * rejects. Call it before `hasPermissions` right after a reload, so an app is not under-granted.
512
+ */
513
+ permissionsReady(): Promise<void>;
471
514
  get did(): string;
472
515
  get sessionDid(): string;
473
516
  get credentialHolderDid(): string;
@@ -568,10 +611,31 @@ export declare class TinyCloudWeb {
568
611
  * `expiryMs` does not apply to them.
569
612
  *
570
613
  * `options.onBehalfOf` names the app the permissions are for when this
571
- * app asks on its behalf; the prompt names both. `options.allowPromptSuppression: false`
572
- * always shows the prompt, ignoring an earlier 30-day opt-out, and offers none.
614
+ * app asks on its behalf; the prompt names both. With it, only the session's own
615
+ * permissions and approvals given for that app count as already covering the request,
616
+ * and a new approval is signed for it even when another app's approval covers the same
617
+ * access. `options.allowPromptSuppression: false`
618
+ * always shows the prompt, ignoring an earlier 30-day opt-out, and offers none; a request
619
+ * to decrypt, create keys or read secrets always does so.
620
+ *
621
+ * The prompt states each entry in plain words derived from the request: the exact resource (for an encryption key,
622
+ * its key path), each action and the expiry. `options.caption` is the app's own short label for the request, such as
623
+ * `"TrustBot's chat history"`; the prompt shows it as plain text beneath that line, attributed to the app, and never
624
+ * in its place. It is cut to 120 characters.
625
+ *
626
+ * An approved request that is not elevated (no decrypt or key creation, nothing in the secrets
627
+ * space, no caveats) is kept with the session and active again after a page reload, with its own
628
+ * signed expiry. An elevated one is not kept across a reload, except a grant made only of exact keys of the owner's
629
+ * own secrets (decrypt and/or key creation, any number of keys), which is kept for its signed expiry.
573
630
  */
574
631
  requestPermissions(additional: PermissionEntry[], options?: RequestPermissionsOptions): Promise<RequestPermissionsResult>;
632
+ /** `requestPermissions`; `keep` stores the issued non-elevated grants beside the session. The panel stores its own. */
633
+ private requestPermissionsKeeping;
634
+ /**
635
+ * Records which app approved each grant. A grant of one of the owner's secrets' own keys is always stored beside the
636
+ * session (TC-3284); the other non-elevated grants are stored when `keep`.
637
+ */
638
+ private keepGrants;
575
639
  /**
576
640
  * The signer a valid `setRuntimePermissionSigner` call bound to the current session, or undefined. A signer bound to a
577
641
  * session that has ended or been replaced is cleared.
@@ -580,12 +644,11 @@ export declare class TinyCloudWeb {
580
644
  /** Whether OpenKey signs the runtime grants: the bound signer declared itself OpenKey, or none is bound and `openkey` is configured. */
581
645
  private runtimeSignedByOpenKey;
582
646
  /**
583
- * Whether OpenKey's own approval shows the request, so the SDK prompt is skipped: a bound signer that declared itself
584
- * OpenKey passes the presentation on; the configured OpenKey client accepts one (`signMessagePresentation` is 1) and
585
- * reports its approval screen shows the request (`signMessageShowsApproval` is true, which an external-wallet key is not).
586
- * Otherwise the SDK prompt is shown as it is for any other signer, with its 30-day option.
647
+ * Whether the configured OpenKey client reports that the connected key signs in an external wallet
648
+ * (`signMessageShowsApproval` is false): OpenKey then shows no approval screen, so the SDK prompt is the one screen.
649
+ * A bound signer declared OpenKey always passes the request on to OpenKey's approval.
587
650
  */
588
- private openKeyShowsApp;
651
+ private openKeySignsInExternalWallet;
589
652
  /**
590
653
  * Signs the SIWE of a runtime permission grant. Precedence: the signer set with `setRuntimePermissionSigner`, then
591
654
  * the configured OpenKey client's byte-exact `signMessage` (an OpenKey session's wallet provider does not implement
@@ -20,6 +20,16 @@ export interface PermissionRequestModalOptions {
20
20
  appIcon?: string;
21
21
  /** The additional permissions the app wants on top of its current session. */
22
22
  additional: PermissionEntry[];
23
+ /**
24
+ * Requested lifetime of the grant, in milliseconds (`requestPermissions` `expiryMs`). Each entry's line states it,
25
+ * or the node's default when absent.
26
+ */
27
+ expiryMs?: number;
28
+ /**
29
+ * The app's own label for this request. Shown as plain text beneath the derived lines, attributed to `appName`; it
30
+ * never replaces them. Trimmed, folded to one line and cut to 120 characters.
31
+ */
32
+ caption?: string;
23
33
  /**
24
34
  * Display name of the app the request is for, when `appName` asks on its
25
35
  * behalf. Names it in the title and the description.
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The plain-words line the permission prompt shows for each requested entry, and the app's optional caption beneath
3
+ * the lines (TC-4222). The line is built only from the request: the exact resource, each action and the grant's
4
+ * lifetime. It is never broader or vaguer than the request; an action it has no words for is shown verbatim.
5
+ * Control, zero-width and direction characters in request-derived text are shown as visible escapes, never as is.
6
+ *
7
+ * Every user-visible string is in {@link PERMISSION_LINE_COPY}.
8
+ */
9
+ import type { PermissionEntry } from "@tinycloud/sdk-core";
10
+ /** All user-visible wording of the derived line and the caption label. */
11
+ export declare const PERMISSION_LINE_COPY: {
12
+ /** One entry's line: `{actions} {resource}, for up to {lifetime}.` */
13
+ readonly line: (actions: string, resource: string, lifetime: string) => string;
14
+ /** An action with no words of its own, named verbatim. */
15
+ readonly unknownAction: (action: string) => string;
16
+ /** Joins the last two actions or lifetime parts. */
17
+ readonly and: "and";
18
+ readonly resource: {
19
+ readonly key: (keyPath: string) => string;
20
+ readonly keyPrefix: (prefix: string) => string;
21
+ readonly network: (name: string) => string;
22
+ readonly exactPath: (path: string) => string;
23
+ readonly pathPrefix: (path: string) => string;
24
+ readonly everything: "everything";
25
+ readonly inSpace: (what: string, space: string) => string;
26
+ };
27
+ /**
28
+ * Action words per service, in the order a line lists them. Each reads before the resource phrase
29
+ * ("decrypt with" + "the key …"). Encryption actions have one set for a key or key prefix and one for a whole network.
30
+ */
31
+ readonly actions: Record<string, Record<string, string>>;
32
+ readonly units: {
33
+ readonly day: readonly ["day", "days"];
34
+ readonly hour: readonly ["hour", "hours"];
35
+ readonly minute: readonly ["minute", "minutes"];
36
+ readonly second: readonly ["second", "seconds"];
37
+ };
38
+ /** Precedes the app's caption, naming the app that wrote it. */
39
+ readonly captionSource: (appName: string) => string;
40
+ /** Technical details of an encryption entry narrower than its network. */
41
+ readonly details: {
42
+ readonly key: {
43
+ readonly scope: "This key only";
44
+ readonly summary: "This permission covers only the key shown below.";
45
+ };
46
+ readonly keyPrefix: {
47
+ readonly scope: "Keys under this prefix only";
48
+ readonly summary: "This permission covers only the keys under the prefix shown below.";
49
+ };
50
+ };
51
+ };
52
+ /** Longest caption shown, in characters; a longer one is cut and ends with "…". */
53
+ export declare const CAPTION_MAX_LENGTH = 120;
54
+ /** Longest description shown as an entry's first line, in characters; a longer one is cut and ends with "…". */
55
+ export declare const DESCRIPTION_MAX_LENGTH = 140;
56
+ /** `text` with every hidden character shown as a visible escape such as `\u{202E}`, so it never reads cleaner than it is. */
57
+ export declare function showHiddenCharacters(text: string): string;
58
+ /** `entry` with its service, space, path and actions passed through {@link showHiddenCharacters}, for display only. */
59
+ export declare function visibleEntry(entry: PermissionEntry): PermissionEntry;
60
+ /**
61
+ * An entry's description as shown: whitespace folded to single spaces and trimmed, then hidden characters shown
62
+ * escaped (see {@link showHiddenCharacters}). `line` is cut to {@link DESCRIPTION_MAX_LENGTH} characters, never
63
+ * inside a character, and `full` is the whole text, set only when `line` is cut. Undefined when nothing is left.
64
+ */
65
+ export declare function visibleDescription(description: unknown): {
66
+ line: string;
67
+ full?: string;
68
+ } | undefined;
69
+ /** Encryption entries' reach: a whole network, keys under a prefix, or one key. Undefined for other services. */
70
+ export type EncryptionReach = {
71
+ kind: "network";
72
+ name: string;
73
+ } | {
74
+ kind: "keyPrefix";
75
+ prefix: string;
76
+ } | {
77
+ kind: "key";
78
+ keyPath: string;
79
+ };
80
+ export declare function encryptionReach(entry: PermissionEntry): EncryptionReach | undefined;
81
+ /** The lifetime the node gives the grant for `entries`, before it is cut to the session's end. */
82
+ export declare function grantLifetimeMs(entries: readonly PermissionEntry[], expiryMs: number | undefined): number;
83
+ /** The plain-words line for one entry, granted for `lifetimeMs`. Hidden characters in the request are shown escaped. */
84
+ export declare function derivePermissionLine(requested: PermissionEntry, lifetimeMs: number): string;
85
+ /**
86
+ * The caption as shown: whitespace folded to single spaces, hidden characters (see {@link showHiddenCharacters})
87
+ * removed, trimmed and cut to {@link CAPTION_MAX_LENGTH} characters. Undefined when nothing is left.
88
+ */
89
+ export declare function normalizeCaption(caption: unknown): string | undefined;
90
+ //# sourceMappingURL=permissionLine.d.ts.map
@@ -0,0 +1,72 @@
1
+ import type { LocationRecordV2, LocationRecordV2Payload, RegistryCacheStore, RegistrySequenceStore, RegistryVerdictCache } from "@tinycloud/sdk-core";
2
+ import type { TinyCloudNode } from "@tinycloud/node-sdk";
3
+ /**
4
+ * Origins that may publish the owner's record: TinyCloud One and Home. OpenKey's
5
+ * registry-record allowlist also signs for secrets.tinycloud.xyz and share.tinycloud.xyz,
6
+ * but the SDK publishes only from these two and returns `"needs-one"` elsewhere without
7
+ * asking for a signature.
8
+ */
9
+ export declare const REGISTRY_PUBLISH_ORIGINS: readonly string[];
10
+ /** True when `error` (or anything in its `cause` chain) is OpenKey's registry-record sign refusal. */
11
+ export declare function isRegistryRecordSignRefusal(error: unknown): boolean;
12
+ /**
13
+ * Outcome of the publish attempt. Returned from `tcw.ensureOwnerRegistryRecord` so the
14
+ * host can react.
15
+ */
16
+ export type RegistryPublishOutcome = "published" | "already-current" | "needs-one" | "unavailable";
17
+ /** A signer that produces an EIP-191 signature over a canonical location-record message for a specific owner `did:pkh`. */
18
+ export interface OwnerMessageSigner {
19
+ readonly subject: string;
20
+ readonly signMessage: (message: string) => Promise<string>;
21
+ }
22
+ export interface EnsureOwnerRegistryRecordOptions {
23
+ node: TinyCloudNode;
24
+ /** Owner's did:pkh, taken from `node.did` in tcw.ts (only computed for wallet / OpenKey owners). */
25
+ subject: string;
26
+ /** The page's origin. Only `REGISTRY_PUBLISH_ORIGINS` may publish. */
27
+ origin: string | undefined;
28
+ /** Registry endpoint. Defaults to `DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL` when undefined; `null` from host config means the registry is explicitly disabled and the publish is skipped. */
29
+ registryUrl?: string | null;
30
+ /** Optional: SDK-side registry stores, so publication uses the same sequences / cache as everything else. */
31
+ registryChainId?: number;
32
+ registrySequenceStore?: RegistrySequenceStore;
33
+ registryCacheStore?: RegistryCacheStore;
34
+ registryVerdictCache?: RegistryVerdictCache;
35
+ /** Resolves the owner signer. Returning `undefined` means we have no way to sign (skip). */
36
+ resolveSigner: () => Promise<OwnerMessageSigner | undefined>;
37
+ /** Host-supplied error hook. Called for every failure before we map the outcome. Never throws. */
38
+ onError?: (error: unknown) => void;
39
+ /**
40
+ * Called after every await the helper issues. Throws when the signed-in session has
41
+ * changed under the helper (sign-out, account switch). Fail-closed: the helper catches
42
+ * the throw, reports via `onError`, and returns `"unavailable"` without writing anything,
43
+ * so a stale call after a sign-out never reaches the registry.
44
+ */
45
+ assertCurrent?: () => void;
46
+ /** Overridable for tests. */
47
+ now?: () => Date;
48
+ /** Overridable for tests; defaults to the globalThis fetch used elsewhere in the SDK. */
49
+ fetch?: typeof fetch;
50
+ }
51
+ /**
52
+ * Called by `tcw.ensureOwnerRegistryRecord` for a `did:pkh` owner. Guards:
53
+ *
54
+ * 1. The registry verdict is read first. Anything but `unregistered` returns
55
+ * `"already-current"`, and an `offline` verdict returns `"unavailable"` because a cold
56
+ * registry cannot prove the owner is absent.
57
+ * 2. An unregistered owner on an origin outside `REGISTRY_PUBLISH_ORIGINS` returns
58
+ * `"needs-one"` before anything is signed.
59
+ * 3. The record's node identity comes only from `node.activeNodeIdentity()`, never from
60
+ * caller input: a signed record pointing at the wrong node is the real attacker gain.
61
+ * 4. An existing record is never overwritten or merged. `publishLocationRecordV2`'s
62
+ * pre-sign re-read refuses the publish if a record has appeared since the verdict.
63
+ * 5. `assertCurrent` runs after each await here and last in `onPrepared`, before the
64
+ * signature prompt. A sign-out or account switch by then throws: nothing is signed or
65
+ * PUT, and the call returns `"unavailable"`. One during the signature prompt or the PUT
66
+ * is not stopped; the PUT goes ahead and the check after it returns `"unavailable"`.
67
+ * 6. OpenKey's registry-record sign refusal maps to `"needs-one"`. Every other error is
68
+ * swallowed and funnelled through `onError`; this never throws.
69
+ */
70
+ export declare function ensureOwnerRegistryRecord(options: EnsureOwnerRegistryRecordOptions): Promise<RegistryPublishOutcome>;
71
+ export type { LocationRecordV2, LocationRecordV2Payload };
72
+ //# sourceMappingURL=registry-publish.d.ts.map
@@ -1 +1 @@
1
- (()=>{"use strict";var e={d:(s,i)=>{for(var t in i)e.o(i,t)&&!e.o(s,t)&&Object.defineProperty(s,t,{enumerable:!0,get:i[t]})},o:(e,s)=>Object.prototype.hasOwnProperty.call(e,s),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},s={};async function i(e,{graph:s,session:i,sessionExpiry:n,expanded:a,options:o}){const{lib:r}=e;if(!e.signer&&void 0===o?.signMessage)throw new Error("grantRuntimePermissions requires wallet mode with a signer or privateKey.");e.assertCaveats(a);const c=a.filter(s=>e.isEncryption(s)||e.isRawRevocation(s)),d=a.filter(s=>!e.isEncryption(s)&&!e.isRawRevocation(s)),g=new Map;for(const s of d){const t=e.resolveSpace(s.space,i),n=g.get(t)??[];n.push(s),g.set(t,n)}0===g.size&&c.length>0&&g.set(i.spaceId,[]);const l=[...g.keys()].filter(e=>{const s=r.parseSpaceUri(e);return void 0===s?.address||s.chainId!==String(i.chainId)||s.address!==r.canonicalizeAddress(i.address)});if(l.length>0)throw Object.assign(new Error(`Runtime permissions can only be granted in this account's own spaces, not ${l.join(", ")}.`),{code:"SPACE_NOT_OWNED",spaceIds:l});const p=new Date,h=r.expiryMs(o?.expiry);let u=new Date(p.getTime()+h);void 0!==n&&n<u&&(u=r.wholeSecond(n)),r.assertExpiry(u,"siwe");const w=[...g.keys()],f=w[0],v=Object.fromEntries([...g].map(([s,i])=>[s,e.abilities(i)])),m=(()=>{try{return e.wasm.prepareSession({abilities:v[f],...w.length>1?{spaceAbilities:v}:{},...c.length>0?{rawAbilities:t(e,c)}:{},address:e.wasm.ensureEip55(i.address),chainId:i.chainId,domain:e.domain,issuedAt:p.toISOString(),expirationTime:u.toISOString(),spaceId:f,jwk:i.jwk})}catch(s){if(c.some(s=>e.isRawRevocation(s))&&/invalid ReCap resource URI/i.test(s instanceof Error?s.message:String(s)))throw Object.assign(new Error("This WASM build cannot encode raw urn:cid ReCap resources."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:s});throw s}})();void 0!==o?.signMessage&&function(e,s,i){let t;try{t=new e.Siwe(s)}catch{throw new Error("The prepared sign-in message is not a valid SIWE message.")}if(t.prepareMessage()!==s)throw new Error("The prepared sign-in message is not in canonical form.");if(t.chainId!==i.chainId||e.canonicalizeAddress(t.address)!==e.canonicalizeAddress(i.address))throw new Error("The prepared sign-in message is for a different account or chain than this session.")}(r,m.siwe,i);const S=void 0!==o?.signMessage?await o.signMessage(m.siwe):await e.signer.signMessage(m.siwe);if(void 0!==o?.signMessage&&!await r.verifySignature(m.siwe,S,i.address))throw new Error("The signature does not match the account that owns this session.");s.assertActive();const E=e.wasm.completeSessionSetup({...m,signature:S});e.retainRoot({delegationHeader:E.delegationHeader,delegationCid:E.delegationCid,spaceId:f,address:i.address,chainId:i.chainId,siwe:m.siwe,signature:S});const R=(s,t)=>{const n=e.resources(t,s),a=n[0];return{cid:E.delegationCid,delegationHeader:E.delegationHeader,spaceId:s,path:a.path,actions:a.actions,resources:n,disableSubDelegation:!1,expiry:u,delegateDID:i.verificationMethod,ownerAddress:i.address,chainId:i.chainId,host:e.host,siweProof:{siwe:m.siwe,signature:S}}},y=await e.activate(E.delegationHeader,w.flatMap((s,i)=>e.activationResources(R(s,[...g.get(s),...0===i?c:[]]))),s.signal).catch(i=>{s.assertActive();const t=i instanceof r.PartialNodeWrite?i.failed.find(({cause:e})=>e instanceof r.ResourceNotRouted)?.cause:void 0;if(void 0!==t)throw t;const n=w.filter(e=>g.get(e).length>0),a=i instanceof r.NodeNotFound&&"registered"===i.verdict.status?i.verdict.record?.spaces.map(({space:e})=>e):void 0;if(void 0!==a&&0===c.length&&n.length>0&&n.every(s=>!a.some(i=>e.spaceIdsEqual(i,s))))throw new r.MissingSpaces(n,[]);throw i}),I=y.success?w.filter(s=>g.get(s).length>0&&y.skipped?.some(i=>e.spaceIdsEqual(i,s))):404===y.status?w.filter(e=>g.get(e).length>0):[];if(!y.success&&0===I.length){if(c.some(s=>e.isRawRevocation(s))&&401===y.status&&/Cannot find parent delegation/i.test(y.error??""))throw Object.assign(new Error("The host cannot activate a root raw-CID revoke authority without a parent delegation."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:y});throw Object.assign(new Error(`Failed to activate runtime permission delegation: ${r.describeFailure(y)}`),{cause:y})}s.assertActive();const b=y.success?w.find(e=>!I.includes(e))??(c.length>0?w[0]:void 0):void 0,M=[];for(const s of w){const t=[...I.includes(s)?[]:g.get(s),...s===b?c:[]];if(0===t.length)continue;const n=R(s,t);e.install({session:{delegationHeader:E.delegationHeader,delegationCid:E.delegationCid,spaceId:s,verificationMethod:i.verificationMethod,jwk:i.jwk},delegation:n,operations:e.operations(t,s),expiresAt:u,provenance:"runtime"}),M.push(n)}if(I.length>0)throw new r.MissingSpaces(I,M);return M}function t(e,s){const i={};for(const t of s){if(e.isRawRevocation(t)){i[t.space]=[...new Set(t.actions)];continue}if(!e.isEncryption(t))continue;const s=i[t.path]??[],n=new Set(s);for(const e of t.actions)n.has(e)||(s.push(e),n.add(e));i[t.path]=s}return i}e.r(s),e.d(s,{issueRuntimeGrants:()=>i}),module.exports=s})();
1
+ (()=>{"use strict";var e={d:(s,i)=>{for(var t in i)e.o(i,t)&&!e.o(s,t)&&Object.defineProperty(s,t,{enumerable:!0,get:i[t]})},o:(e,s)=>Object.prototype.hasOwnProperty.call(e,s),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},s={};async function i(e,{graph:s,session:i,sessionExpiry:n,expanded:a,options:o}){const{lib:r}=e;if(!e.signer&&void 0===o?.signMessage)throw new Error("grantRuntimePermissions requires wallet mode with a signer or privateKey.");e.assertCaveats(a);const c=a.filter(s=>e.isEncryption(s)||e.isRawRevocation(s)),d=a.filter(s=>!e.isEncryption(s)&&!e.isRawRevocation(s)),g=new Map;for(const s of d){const t=e.resolveSpace(s.space,i),n=g.get(t)??[];n.push(s),g.set(t,n)}0===g.size&&c.length>0&&g.set(i.spaceId,[]);const l=[...g.keys()].filter(e=>{const s=r.parseSpaceUri(e);return void 0===s?.address||s.chainId!==String(i.chainId)||s.address!==r.canonicalizeAddress(i.address)});if(l.length>0)throw Object.assign(new Error(`Runtime permissions can only be granted in this account's own spaces, not ${l.join(", ")}.`),{code:"SPACE_NOT_OWNED",spaceIds:l});const p=new Date,h=a.some(r.isSecretKey)?r.secretKeyExpiryMs(o?.expiry):r.expiryMs(o?.expiry);let u=new Date(p.getTime()+h);void 0!==n&&n<u&&(u=r.wholeSecond(n)),r.assertExpiry(u,"siwe");const w=[...g.keys()],f=w[0],v=Object.fromEntries([...g].map(([s,i])=>[s,e.abilities(i)])),m=(()=>{try{return e.wasm.prepareSession({abilities:v[f],...w.length>1?{spaceAbilities:v}:{},...c.length>0?{rawAbilities:t(e,c)}:{},address:e.wasm.ensureEip55(i.address),chainId:i.chainId,domain:e.domain,issuedAt:p.toISOString(),expirationTime:u.toISOString(),spaceId:f,jwk:i.jwk})}catch(s){if(c.some(s=>e.isRawRevocation(s))&&/invalid ReCap resource URI/i.test(s instanceof Error?s.message:String(s)))throw Object.assign(new Error("This WASM build cannot encode raw urn:cid ReCap resources."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:s});throw s}})();void 0!==o?.signMessage&&function(e,s,i){let t;try{t=new e.Siwe(s)}catch{throw new Error("The prepared sign-in message is not a valid SIWE message.")}if(t.prepareMessage()!==s)throw new Error("The prepared sign-in message is not in canonical form.");if(t.chainId!==i.chainId||e.canonicalizeAddress(t.address)!==e.canonicalizeAddress(i.address))throw new Error("The prepared sign-in message is for a different account or chain than this session.")}(r,m.siwe,i);const S=void 0!==o?.signMessage?await o.signMessage(m.siwe):await e.signer.signMessage(m.siwe);if(void 0!==o?.signMessage&&!await r.verifySignature(m.siwe,S,i.address))throw new Error("The signature does not match the account that owns this session.");s.assertActive();const y=e.wasm.completeSessionSetup({...m,signature:S});e.retainRoot({delegationHeader:y.delegationHeader,delegationCid:y.delegationCid,spaceId:f,address:i.address,chainId:i.chainId,siwe:m.siwe,signature:S});const E=(s,t)=>{const n=e.resources(t,s),a=n[0];return{cid:y.delegationCid,delegationHeader:y.delegationHeader,spaceId:s,path:a.path,actions:a.actions,resources:n,disableSubDelegation:!1,expiry:u,delegateDID:i.verificationMethod,ownerAddress:i.address,chainId:i.chainId,host:e.host,siweProof:{siwe:m.siwe,signature:S}}},R=await e.activate(y.delegationHeader,w.flatMap((s,i)=>e.activationResources(E(s,[...g.get(s),...0===i?c:[]]))),s.signal).catch(i=>{s.assertActive();const t=i instanceof r.PartialNodeWrite?i.failed.find(({cause:e})=>e instanceof r.ResourceNotRouted)?.cause:void 0;if(void 0!==t)throw t;const n=w.filter(e=>g.get(e).length>0),a=i instanceof r.NodeNotFound&&"registered"===i.verdict.status?i.verdict.record?.spaces.map(({space:e})=>e):void 0;if(void 0!==a&&0===c.length&&n.length>0&&n.every(s=>!a.some(i=>e.spaceIdsEqual(i,s))))throw new r.MissingSpaces(n,[]);throw i}),I=R.success?w.filter(s=>g.get(s).length>0&&R.skipped?.some(i=>e.spaceIdsEqual(i,s))):404===R.status?w.filter(e=>g.get(e).length>0):[];if(!R.success&&0===I.length){if(c.some(s=>e.isRawRevocation(s))&&401===R.status&&/Cannot find parent delegation/i.test(R.error??""))throw Object.assign(new Error("The host cannot activate a root raw-CID revoke authority without a parent delegation."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:R});throw Object.assign(new Error(`Failed to activate runtime permission delegation: ${r.describeFailure(R)}`),{cause:R})}s.assertActive();const b=R.success?w.find(e=>!I.includes(e))??(c.length>0?w[0]:void 0):void 0,M=[];for(const s of w){const t=[...I.includes(s)?[]:g.get(s),...s===b?c:[]];if(0===t.length)continue;const n=E(s,t);e.install({session:{delegationHeader:y.delegationHeader,delegationCid:y.delegationCid,spaceId:s,verificationMethod:i.verificationMethod,jwk:i.jwk},delegation:n,operations:e.operations(t,s),expiresAt:u,provenance:"runtime"}),M.push(n)}if(I.length>0)throw new r.MissingSpaces(I,M);return M}function t(e,s){const i={};for(const t of s){if(e.isRawRevocation(t)){i[t.space]=[...new Set(t.actions)];continue}if(!e.isEncryption(t))continue;const s=i[t.path]??[],n=new Set(s);for(const e of t.actions)n.has(e)||(s.push(e),n.add(e));i[t.path]=s}return i}e.r(s),e.d(s,{issueRuntimeGrants:()=>i}),module.exports=s})();
@@ -1 +1 @@
1
- var e={};async function s(e,{graph:s,session:t,sessionExpiry:n,expanded:a,options:o}){const{lib:r}=e;if(!e.signer&&void 0===o?.signMessage)throw new Error("grantRuntimePermissions requires wallet mode with a signer or privateKey.");e.assertCaveats(a);const c=a.filter(s=>e.isEncryption(s)||e.isRawRevocation(s)),d=a.filter(s=>!e.isEncryption(s)&&!e.isRawRevocation(s)),g=new Map;for(const s of d){const i=e.resolveSpace(s.space,t),n=g.get(i)??[];n.push(s),g.set(i,n)}0===g.size&&c.length>0&&g.set(t.spaceId,[]);const h=[...g.keys()].filter(e=>{const s=r.parseSpaceUri(e);return void 0===s?.address||s.chainId!==String(t.chainId)||s.address!==r.canonicalizeAddress(t.address)});if(h.length>0)throw Object.assign(new Error(`Runtime permissions can only be granted in this account's own spaces, not ${h.join(", ")}.`),{code:"SPACE_NOT_OWNED",spaceIds:h});const l=new Date,p=r.expiryMs(o?.expiry);let w=new Date(l.getTime()+p);void 0!==n&&n<w&&(w=r.wholeSecond(n)),r.assertExpiry(w,"siwe");const u=[...g.keys()],f=u[0],v=Object.fromEntries([...g].map(([s,i])=>[s,e.abilities(i)])),m=(()=>{try{return e.wasm.prepareSession({abilities:v[f],...u.length>1?{spaceAbilities:v}:{},...c.length>0?{rawAbilities:i(e,c)}:{},address:e.wasm.ensureEip55(t.address),chainId:t.chainId,domain:e.domain,issuedAt:l.toISOString(),expirationTime:w.toISOString(),spaceId:f,jwk:t.jwk})}catch(s){if(c.some(s=>e.isRawRevocation(s))&&/invalid ReCap resource URI/i.test(s instanceof Error?s.message:String(s)))throw Object.assign(new Error("This WASM build cannot encode raw urn:cid ReCap resources."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:s});throw s}})();void 0!==o?.signMessage&&function(e,s,i){let t;try{t=new e.Siwe(s)}catch{throw new Error("The prepared sign-in message is not a valid SIWE message.")}if(t.prepareMessage()!==s)throw new Error("The prepared sign-in message is not in canonical form.");if(t.chainId!==i.chainId||e.canonicalizeAddress(t.address)!==e.canonicalizeAddress(i.address))throw new Error("The prepared sign-in message is for a different account or chain than this session.")}(r,m.siwe,t);const E=void 0!==o?.signMessage?await o.signMessage(m.siwe):await e.signer.signMessage(m.siwe);if(void 0!==o?.signMessage&&!await r.verifySignature(m.siwe,E,t.address))throw new Error("The signature does not match the account that owns this session.");s.assertActive();const R=e.wasm.completeSessionSetup({...m,signature:E});e.retainRoot({delegationHeader:R.delegationHeader,delegationCid:R.delegationCid,spaceId:f,address:t.address,chainId:t.chainId,siwe:m.siwe,signature:E});const S=(s,i)=>{const n=e.resources(i,s),a=n[0];return{cid:R.delegationCid,delegationHeader:R.delegationHeader,spaceId:s,path:a.path,actions:a.actions,resources:n,disableSubDelegation:!1,expiry:w,delegateDID:t.verificationMethod,ownerAddress:t.address,chainId:t.chainId,host:e.host,siweProof:{siwe:m.siwe,signature:E}}},I=await e.activate(R.delegationHeader,u.flatMap((s,i)=>e.activationResources(S(s,[...g.get(s),...0===i?c:[]]))),s.signal).catch(i=>{s.assertActive();const t=i instanceof r.PartialNodeWrite?i.failed.find(({cause:e})=>e instanceof r.ResourceNotRouted)?.cause:void 0;if(void 0!==t)throw t;const n=u.filter(e=>g.get(e).length>0),a=i instanceof r.NodeNotFound&&"registered"===i.verdict.status?i.verdict.record?.spaces.map(({space:e})=>e):void 0;if(void 0!==a&&0===c.length&&n.length>0&&n.every(s=>!a.some(i=>e.spaceIdsEqual(i,s))))throw new r.MissingSpaces(n,[]);throw i}),y=I.success?u.filter(s=>g.get(s).length>0&&I.skipped?.some(i=>e.spaceIdsEqual(i,s))):404===I.status?u.filter(e=>g.get(e).length>0):[];if(!I.success&&0===y.length){if(c.some(s=>e.isRawRevocation(s))&&401===I.status&&/Cannot find parent delegation/i.test(I.error??""))throw Object.assign(new Error("The host cannot activate a root raw-CID revoke authority without a parent delegation."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:I});throw Object.assign(new Error(`Failed to activate runtime permission delegation: ${r.describeFailure(I)}`),{cause:I})}s.assertActive();const b=I.success?u.find(e=>!y.includes(e))??(c.length>0?u[0]:void 0):void 0,A=[];for(const s of u){const i=[...y.includes(s)?[]:g.get(s),...s===b?c:[]];if(0===i.length)continue;const n=S(s,i);e.install({session:{delegationHeader:R.delegationHeader,delegationCid:R.delegationCid,spaceId:s,verificationMethod:t.verificationMethod,jwk:t.jwk},delegation:n,operations:e.operations(i,s),expiresAt:w,provenance:"runtime"}),A.push(n)}if(y.length>0)throw new r.MissingSpaces(y,A);return A}function i(e,s){const i={};for(const t of s){if(e.isRawRevocation(t)){i[t.space]=[...new Set(t.actions)];continue}if(!e.isEncryption(t))continue;const s=i[t.path]??[],n=new Set(s);for(const e of t.actions)n.has(e)||(s.push(e),n.add(e));i[t.path]=s}return i}e.d=(s,i)=>{for(var t in i)e.o(i,t)&&!e.o(s,t)&&Object.defineProperty(s,t,{enumerable:!0,get:i[t]})},e.o=(e,s)=>Object.prototype.hasOwnProperty.call(e,s);export{s as issueRuntimeGrants};
1
+ var e={};async function s(e,{graph:s,session:t,sessionExpiry:n,expanded:a,options:o}){const{lib:r}=e;if(!e.signer&&void 0===o?.signMessage)throw new Error("grantRuntimePermissions requires wallet mode with a signer or privateKey.");e.assertCaveats(a);const c=a.filter(s=>e.isEncryption(s)||e.isRawRevocation(s)),d=a.filter(s=>!e.isEncryption(s)&&!e.isRawRevocation(s)),g=new Map;for(const s of d){const i=e.resolveSpace(s.space,t),n=g.get(i)??[];n.push(s),g.set(i,n)}0===g.size&&c.length>0&&g.set(t.spaceId,[]);const p=[...g.keys()].filter(e=>{const s=r.parseSpaceUri(e);return void 0===s?.address||s.chainId!==String(t.chainId)||s.address!==r.canonicalizeAddress(t.address)});if(p.length>0)throw Object.assign(new Error(`Runtime permissions can only be granted in this account's own spaces, not ${p.join(", ")}.`),{code:"SPACE_NOT_OWNED",spaceIds:p});const h=new Date,l=a.some(r.isSecretKey)?r.secretKeyExpiryMs(o?.expiry):r.expiryMs(o?.expiry);let w=new Date(h.getTime()+l);void 0!==n&&n<w&&(w=r.wholeSecond(n)),r.assertExpiry(w,"siwe");const u=[...g.keys()],f=u[0],v=Object.fromEntries([...g].map(([s,i])=>[s,e.abilities(i)])),m=(()=>{try{return e.wasm.prepareSession({abilities:v[f],...u.length>1?{spaceAbilities:v}:{},...c.length>0?{rawAbilities:i(e,c)}:{},address:e.wasm.ensureEip55(t.address),chainId:t.chainId,domain:e.domain,issuedAt:h.toISOString(),expirationTime:w.toISOString(),spaceId:f,jwk:t.jwk})}catch(s){if(c.some(s=>e.isRawRevocation(s))&&/invalid ReCap resource URI/i.test(s instanceof Error?s.message:String(s)))throw Object.assign(new Error("This WASM build cannot encode raw urn:cid ReCap resources."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:s});throw s}})();void 0!==o?.signMessage&&function(e,s,i){let t;try{t=new e.Siwe(s)}catch{throw new Error("The prepared sign-in message is not a valid SIWE message.")}if(t.prepareMessage()!==s)throw new Error("The prepared sign-in message is not in canonical form.");if(t.chainId!==i.chainId||e.canonicalizeAddress(t.address)!==e.canonicalizeAddress(i.address))throw new Error("The prepared sign-in message is for a different account or chain than this session.")}(r,m.siwe,t);const E=void 0!==o?.signMessage?await o.signMessage(m.siwe):await e.signer.signMessage(m.siwe);if(void 0!==o?.signMessage&&!await r.verifySignature(m.siwe,E,t.address))throw new Error("The signature does not match the account that owns this session.");s.assertActive();const R=e.wasm.completeSessionSetup({...m,signature:E});e.retainRoot({delegationHeader:R.delegationHeader,delegationCid:R.delegationCid,spaceId:f,address:t.address,chainId:t.chainId,siwe:m.siwe,signature:E});const S=(s,i)=>{const n=e.resources(i,s),a=n[0];return{cid:R.delegationCid,delegationHeader:R.delegationHeader,spaceId:s,path:a.path,actions:a.actions,resources:n,disableSubDelegation:!1,expiry:w,delegateDID:t.verificationMethod,ownerAddress:t.address,chainId:t.chainId,host:e.host,siweProof:{siwe:m.siwe,signature:E}}},y=await e.activate(R.delegationHeader,u.flatMap((s,i)=>e.activationResources(S(s,[...g.get(s),...0===i?c:[]]))),s.signal).catch(i=>{s.assertActive();const t=i instanceof r.PartialNodeWrite?i.failed.find(({cause:e})=>e instanceof r.ResourceNotRouted)?.cause:void 0;if(void 0!==t)throw t;const n=u.filter(e=>g.get(e).length>0),a=i instanceof r.NodeNotFound&&"registered"===i.verdict.status?i.verdict.record?.spaces.map(({space:e})=>e):void 0;if(void 0!==a&&0===c.length&&n.length>0&&n.every(s=>!a.some(i=>e.spaceIdsEqual(i,s))))throw new r.MissingSpaces(n,[]);throw i}),I=y.success?u.filter(s=>g.get(s).length>0&&y.skipped?.some(i=>e.spaceIdsEqual(i,s))):404===y.status?u.filter(e=>g.get(e).length>0):[];if(!y.success&&0===I.length){if(c.some(s=>e.isRawRevocation(s))&&401===y.status&&/Cannot find parent delegation/i.test(y.error??""))throw Object.assign(new Error("The host cannot activate a root raw-CID revoke authority without a parent delegation."),{code:"RAW_RECAP_RESOURCE_UNSUPPORTED",cause:y});throw Object.assign(new Error(`Failed to activate runtime permission delegation: ${r.describeFailure(y)}`),{cause:y})}s.assertActive();const b=y.success?u.find(e=>!I.includes(e))??(c.length>0?u[0]:void 0):void 0,A=[];for(const s of u){const i=[...I.includes(s)?[]:g.get(s),...s===b?c:[]];if(0===i.length)continue;const n=S(s,i);e.install({session:{delegationHeader:R.delegationHeader,delegationCid:R.delegationCid,spaceId:s,verificationMethod:t.verificationMethod,jwk:t.jwk},delegation:n,operations:e.operations(i,s),expiresAt:w,provenance:"runtime"}),A.push(n)}if(I.length>0)throw new r.MissingSpaces(I,A);return A}function i(e,s){const i={};for(const t of s){if(e.isRawRevocation(t)){i[t.space]=[...new Set(t.actions)];continue}if(!e.isEncryption(t))continue;const s=i[t.path]??[],n=new Set(s);for(const e of t.actions)n.has(e)||(s.push(e),n.add(e));i[t.path]=s}return i}e.d=(s,i)=>{for(var t in i)e.o(i,t)&&!e.o(s,t)&&Object.defineProperty(s,t,{enumerable:!0,get:i[t]})},e.o=(e,s)=>Object.prototype.hasOwnProperty.call(e,s);export{s as issueRuntimeGrants};
@@ -1 +1 @@
1
- (()=>{"use strict";var e={d:(t,r)=>{for(var a in r)e.o(r,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:r[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function r(e,t,r,i){if(!t)throw new Error("This delegated access was created without encryption.");const s=t.encryption();s.initialize(e),e.registerService("encryption",s),r.initialize(e);const n=t.vault(r,s);return n.initialize(e),{encryption:s,read:async e=>a(await n.readNetworkEncrypted(e),i)}}function a(e,t){if("ok"!==e.status){if("permission_required"===e.status){const r=t(e.hint);return void 0===r?{status:"read_failed"}:{status:"permission_required",hint:{service:r.service,...void 0===r.space?{}:{space:r.space},path:r.path,actions:[...r.actions]}}}return"aad_mismatch"===e.status?{status:"read_failed"}:{status:e.status}}return"object"==typeof(r=e.entry.value)&&null!==r&&"value"in r&&"string"==typeof r.value&&"createdAt"in r&&"string"==typeof r.createdAt&&"updatedAt"in r&&"string"==typeof r.updatedAt?{status:"ok",value:e.entry.value.value}:{status:"invalid_payload"};var r}e.r(t),e.d(t,{delegatedSecrets:()=>r,secretReadResult:()=>a}),module.exports=t})();
1
+ (()=>{"use strict";var e={d:(t,r)=>{for(var a in r)e.o(r,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:r[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function r(e,t,r,i){if(!t)throw new Error("This delegated access was created without encryption.");const s=t.encryption();s.initialize(e),e.registerService("encryption",s),r.initialize(e);const n=t.vault(r,s);return n.initialize(e),{encryption:s,read:async(e,t)=>a(await n.readNetworkEncrypted(e,t),i)}}function a(e,t){if("ok"!==e.status){if("permission_required"===e.status){const r=t(e.hint);return void 0===r?{status:"read_failed"}:{status:"permission_required",hint:{service:r.service,...void 0===r.space?{}:{space:r.space},path:r.path,actions:[...r.actions]}}}return"aad_mismatch"===e.status?{status:"read_failed"}:{status:e.status}}return"object"==typeof(r=e.entry.value)&&null!==r&&"value"in r&&"string"==typeof r.value&&"createdAt"in r&&"string"==typeof r.createdAt&&"updatedAt"in r&&"string"==typeof r.updatedAt?{status:"ok",value:e.entry.value.value}:{status:"invalid_payload"};var r}e.r(t),e.d(t,{delegatedSecrets:()=>r,secretReadResult:()=>a}),module.exports=t})();
@@ -1 +1 @@
1
- var t={};function e(t,e,i,r){if(!e)throw new Error("This delegated access was created without encryption.");const n=e.encryption();n.initialize(t),t.registerService("encryption",n),i.initialize(t);const s=e.vault(i,n);return s.initialize(t),{encryption:n,read:async t=>a(await s.readNetworkEncrypted(t),r)}}function a(t,e){if("ok"!==t.status){if("permission_required"===t.status){const a=e(t.hint);return void 0===a?{status:"read_failed"}:{status:"permission_required",hint:{service:a.service,...void 0===a.space?{}:{space:a.space},path:a.path,actions:[...a.actions]}}}return"aad_mismatch"===t.status?{status:"read_failed"}:{status:t.status}}return"object"==typeof(a=t.entry.value)&&null!==a&&"value"in a&&"string"==typeof a.value&&"createdAt"in a&&"string"==typeof a.createdAt&&"updatedAt"in a&&"string"==typeof a.updatedAt?{status:"ok",value:t.entry.value.value}:{status:"invalid_payload"};var a}t.d=(e,a)=>{for(var i in a)t.o(a,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:a[i]})},t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);export{e as delegatedSecrets,a as secretReadResult};
1
+ var t={};function e(t,e,i,r){if(!e)throw new Error("This delegated access was created without encryption.");const n=e.encryption();n.initialize(t),t.registerService("encryption",n),i.initialize(t);const s=e.vault(i,n);return s.initialize(t),{encryption:n,read:async(t,e)=>a(await s.readNetworkEncrypted(t,e),r)}}function a(t,e){if("ok"!==t.status){if("permission_required"===t.status){const a=e(t.hint);return void 0===a?{status:"read_failed"}:{status:"permission_required",hint:{service:a.service,...void 0===a.space?{}:{space:a.space},path:a.path,actions:[...a.actions]}}}return"aad_mismatch"===t.status?{status:"read_failed"}:{status:t.status}}return"object"==typeof(a=t.entry.value)&&null!==a&&"value"in a&&"string"==typeof a.value&&"createdAt"in a&&"string"==typeof a.createdAt&&"updatedAt"in a&&"string"==typeof a.updatedAt?{status:"ok",value:t.entry.value.value}:{status:"invalid_payload"};var a}t.d=(e,a)=>{for(var i in a)t.o(a,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:a[i]})},t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);export{e as delegatedSecrets,a as secretReadResult};
@@ -1,3 +1,3 @@
1
1
  /** Space hosting probe and space creation, loaded when the first hosting check or creation runs. */
2
- export { askSpaceHosting, createPrimarySpace, withHostExpiry } from "@tinycloud/node-sdk/space-hosting";
2
+ export { askSpaceHosting, assessHostedOwnerRecap, createPrimarySpace, hostedOwnerPlanOperations, readHostedOwnerSpace, selectHostedOwnerRead, withHostExpiry, } from "@tinycloud/node-sdk/space-hosting";
3
3
  //# sourceMappingURL=space-hosting-entry.d.ts.map
@@ -1 +1 @@
1
- (()=>{"use strict";var e={d:(t,a)=>{for(var s in a)e.o(a,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:a[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{askSpaceHosting:()=>u,createPrimarySpace:()=>w,withHostExpiry:()=>f});var a=new WeakMap,s=5e3,n="tinycloud.kv/list",o="tinycloud.kv/metadata",i="tinycloud.kv/get",r="tinycloud.space/info",c=e=>""===e||e.endsWith("/")||e.endsWith("/*")||e.endsWith("/**"),d=e=>e.endsWith("/**")?e.slice(0,-2):e.endsWith("/*")?e.slice(0,-1):"/"===e?"":e,p=e=>c(e)?`${d(e)}.tinycloud-space-probe`:e;async function h(e,t){try{const{spaceId:a}=e,n=await e.fetch(`${e.host}/invoke`,{method:"POST",headers:{...e.sign([{spaceId:a,service:t.service,path:t.path,action:t.action}]),...t.headers},body:t.body,signal:AbortSignal.timeout(s)});return n.ok?(n.body instanceof ReadableStream&&await n.body.cancel().catch(()=>{}),"hosted"):401===n.status||403===n.status?"refused":404===n.status?/space not found/i.test(await n.text())?"not-hosted":"hosted":"unknown"}catch{return"unknown"}}async function u(e){const t=function({spaceId:e,operations:t,covers:a}){const s=t.filter(t=>!t.caveats?.length&&a(t,{spaceId:e,service:t.service,path:t.path,action:t.action})),h=(t,n)=>s.filter(s=>a(s,{spaceId:e,service:t,path:s.path,action:n}));return[...h("kv",n).map(e=>({service:"kv",path:c(e.path)?d(e.path):e.path,action:n,headers:{"x-tinycloud-limit":"1"}})),...h("kv",o).map(e=>({service:"kv",path:p(e.path),action:o})),...h("space",r).map(()=>({service:"space",path:"",action:r,body:"{}"})),...h("kv",i).map(e=>({service:"kv",path:p(e.path),action:i}))].find(t=>s.some(s=>a(s,{spaceId:e,service:t.service,path:t.path,action:t.action})))}(e);if(!t)return"unknown";const u=`${e.host} ${e.spaceId.replace(/^(tinycloud:pkh:eip155:\d+:)(0x[0-9a-fA-F]{40})/,(e,t,a)=>t+a.toLowerCase())}`;if(a.get(e.scope)?.has(u))return"hosted";let l=await h(e,t);if("refused"===l){try{await e.activate(AbortSignal.timeout(s))}catch{return"unknown"}l=await h(e,t)}return"hosted"===l&&a.set(e.scope,(a.get(e.scope)??new Set).add(u)),"refused"===l?"unknown":l}function l(e){const t=e.error?.trim();return t?`${e.status} - ${t}`:`${e.status}`}async function w({handler:e,session:t,context:a,currentSession:s,signerAddress:n,resolveHost:o,domain:i,hostName:r,guard:c,host:d,onHosted:p,activate:h,signal:u}){const w=()=>{if(u?.throwIfAborted(),t&&s?.()!==t)throw new Error("Space hosting session changed")};if(w(),t&&n&&(await n()).toLowerCase()!==t.address.toLowerCase())return;w();const f=a??(t&&{address:t.address,chainId:t.chainId,spaceId:t.spaceId,host:await(o?.())??r??""});if(!f)throw new Error("Space hosting requires a session context");w(),await c(f),w();const m=await e.confirmSpaceCreation(f);if(w(),!m)return;try{const e=await d(f,w,e=>({address:f.address,chainId:f.chainId,domain:i??"",issuedAt:(new Date).toISOString(),spaceId:f.spaceId,peerId:e}));if(!e.success)throw Object.assign(new Error(`Failed to create space ${f.spaceId}: ${l(e)}`),{cause:e})}catch(t){throw e.onSpaceCreationFailed?.(f,t instanceof Error?t:new Error(String(t))),t}w(),p(f),await new Promise(e=>setTimeout(e,100)),w();const g=await h(f);if(w(),!g.success){const t=Object.assign(new Error(`Failed to activate session after creating space: ${l(g)}`),{cause:g});throw e.onSpaceCreationFailed?.(f,t),t}e.onSpaceCreated?.(f)}function f(e,t,a,s){if(/[\r\u0085\u2028\u2029]/.test(e))throw new Error("Host SIWE contains an unsupported line separator");const n=e.split("\n");if(n.some(e=>e.startsWith("Expiration Time:")))throw new Error("Host SIWE already contains Expiration Time");const o=""===n[3]?4:5,i=o+4;if(!n[o]?.startsWith("URI: ")||!n[i]?.startsWith("Issued At: "))throw new Error("Host SIWE has no positional Issued At field");const r=new Date(t),c=r.getUTCDate();r.setUTCDate(1),r.setUTCFullYear(r.getUTCFullYear()+a);const d=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth()+1,0)).getUTCDate();r.setUTCDate(Math.min(c,d));const p=void 0===s?r.getTime():Date.parse(s);if(!Number.isFinite(p)||p<=t.getTime())throw new Error("Host expiry must be a valid future timestamp");const h=new Date(Math.min(p,r.getTime())).toISOString();return n.splice(i+1,0,`Expiration Time: ${h}`),n.join("\n")}module.exports=t})();
1
+ (()=>{"use strict";var e={d:(t,a)=>{for(var s in a)e.o(a,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:a[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{askSpaceHosting:()=>h,assessHostedOwnerRecap:()=>y,createPrimarySpace:()=>b,hostedOwnerPlanOperations:()=>w,readHostedOwnerSpace:()=>m,selectHostedOwnerRead:()=>v,withHostExpiry:()=>I});var a=new WeakMap,s=5e3,o="tinycloud.kv/list",n="tinycloud.kv/metadata",r="tinycloud.kv/get",i="tinycloud.space/info",c=e=>""===e||e.endsWith("/")||e.endsWith("/*")||e.endsWith("/**"),d=e=>e.endsWith("/**")?e.slice(0,-2):e.endsWith("/*")?e.slice(0,-1):"/"===e?"":e,p=e=>c(e)?`${d(e)}.tinycloud-space-probe`:e;async function u(e,t){try{const{spaceId:a}=e,o=await e.fetch(`${e.host}/invoke`,{method:"POST",headers:{...e.sign([{spaceId:a,service:t.service,path:t.path,action:t.action}]),...t.headers},body:t.body,signal:AbortSignal.timeout(s)});return o.ok?(o.body instanceof ReadableStream&&await o.body.cancel().catch(()=>{}),"hosted"):401===o.status||403===o.status?"refused":404===o.status?/space not found/i.test(await o.text())?"not-hosted":"hosted":"unknown"}catch{return"unknown"}}async function h(e){const t=function({spaceId:e,operations:t,covers:a}){const s=t.filter(t=>!t.caveats?.length&&a(t,{spaceId:e,service:t.service,path:t.path,action:t.action})),u=(t,o)=>s.filter(s=>a(s,{spaceId:e,service:t,path:s.path,action:o}));return[...u("kv",o).map(e=>({service:"kv",path:c(e.path)?d(e.path):e.path,action:o,headers:{"x-tinycloud-limit":"1"}})),...u("kv",n).map(e=>({service:"kv",path:p(e.path),action:n})),...u("space",i).map(()=>({service:"space",path:"",action:i,body:"{}"})),...u("kv",r).map(e=>({service:"kv",path:p(e.path),action:r}))].find(t=>s.some(s=>a(s,{spaceId:e,service:t.service,path:t.path,action:t.action})))}(e);if(!t)return"unknown";const h=`${e.host} ${e.spaceId.replace(/^(tinycloud:pkh:eip155:\d+:)(0x[0-9a-fA-F]{40})/,(e,t,a)=>t+a.toLowerCase())}`;if(a.get(e.scope)?.has(h))return"hosted";let l=await u(e,t);if("refused"===l){try{await e.activate(AbortSignal.timeout(s))}catch{return"unknown"}l=await u(e,t)}return"hosted"===l&&a.set(e.scope,(a.get(e.scope)??new Set).add(h)),"refused"===l?"unknown":l}function l(e,t){const a=e=>e.replace(/^(tinycloud:pkh:eip155:\d+:)(0x[0-9a-fA-F]{40})/,(e,t,a)=>t+a.toLowerCase());return a(e)===a(t)}var f="tinycloud.space/";function w(e){const t=[],a=(e,a)=>{for(const[s,o]of Object.entries(a))for(const[a,n]of Object.entries(o))for(const o of n)t.push({spaceId:e,service:s,path:a,action:o.includes("/")?o:`tinycloud.${s}/${o}`})};a(e.spaceId,e.abilities);for(const[t,s]of Object.entries(e.spaceAbilities??{}))a(t,s);for(const[a,s]of Object.entries(e.rawAbilities??{}))for(const e of s)t.push({resource:a,service:"encryption",path:a,action:e});return t}function v(e,t){const a=e.filter(e=>void 0===e.resource&&void 0!==e.spaceId&&l(e.spaceId,t)&&!e.caveats?.length),s=a.find(e=>"kv"===e.service&&e.action===o);return s?{service:"kv",path:c(s.path)?d(s.path):s.path,action:o,headers:{"x-tinycloud-limit":"1"}}:a.some(e=>"space"===e.service&&e.action===i)?{service:"space",path:"",action:i,body:"{}"}:void 0}function y(e,t){for(const a of e){if(void 0!==a.resource||void 0===a.spaceId||!l(a.spaceId,t))return;if(a.caveats?.length)return;if(a.action.startsWith(f)&&a.action!==i)return;if(/[./]create$/.test(a.action))return}return v(e,t)}async function m(e){const{spaceId:t,read:a}=e;try{const o=await e.fetch(`${e.host}/invoke`,{method:"POST",headers:{...e.sign([{spaceId:t,service:a.service,path:a.path,action:a.action}]),...a.headers},body:a.body,redirect:"error",signal:AbortSignal.timeout(s)});return o.body instanceof ReadableStream&&await o.body.cancel().catch(()=>{}),o.status>=200&&o.status<300?"positive":o.status>=500?"unreachable":"refused"}catch{return"unreachable"}}function g(e){const t=e.error?.trim();return t?`${e.status} - ${t}`:`${e.status}`}async function b({handler:e,session:t,context:a,currentSession:s,signerAddress:o,resolveHost:n,domain:r,hostName:i,guard:c,host:d,onHosted:p,activate:u,signal:h}){const l=()=>{if(h?.throwIfAborted(),t&&s?.()!==t)throw new Error("Space hosting session changed")};if(l(),t&&o&&(await o()).toLowerCase()!==t.address.toLowerCase())return;l();const f=a??(t&&{address:t.address,chainId:t.chainId,spaceId:t.spaceId,host:await(n?.())??i??""});if(!f)throw new Error("Space hosting requires a session context");l(),await c(f),l();const w=await e.confirmSpaceCreation(f);if(l(),!w)return;try{const e=await d(f,l,e=>({address:f.address,chainId:f.chainId,domain:r??"",issuedAt:(new Date).toISOString(),spaceId:f.spaceId,peerId:e}));if(!e.success)throw Object.assign(new Error(`Failed to create space ${f.spaceId}: ${g(e)}`),{cause:e})}catch(t){throw e.onSpaceCreationFailed?.(f,t instanceof Error?t:new Error(String(t))),t}l(),p(f),await new Promise(e=>setTimeout(e,100)),l();const v=await u(f);if(l(),!v.success){const t=Object.assign(new Error(`Failed to activate session after creating space: ${g(v)}`),{cause:v});throw e.onSpaceCreationFailed?.(f,t),t}e.onSpaceCreated?.(f)}function I(e,t,a,s){if(/[\r\u0085\u2028\u2029]/.test(e))throw new Error("Host SIWE contains an unsupported line separator");const o=e.split("\n");if(o.some(e=>e.startsWith("Expiration Time:")))throw new Error("Host SIWE already contains Expiration Time");const n=""===o[3]?4:5,r=n+4;if(!o[n]?.startsWith("URI: ")||!o[r]?.startsWith("Issued At: "))throw new Error("Host SIWE has no positional Issued At field");const i=new Date(t),c=i.getUTCDate();i.setUTCDate(1),i.setUTCFullYear(i.getUTCFullYear()+a);const d=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth()+1,0)).getUTCDate();i.setUTCDate(Math.min(c,d));const p=void 0===s?i.getTime():Date.parse(s);if(!Number.isFinite(p)||p<=t.getTime())throw new Error("Host expiry must be a valid future timestamp");const u=new Date(Math.min(p,i.getTime())).toISOString();return o.splice(r+1,0,`Expiration Time: ${u}`),o.join("\n")}module.exports=t})();