@minca/core 0.1.15 → 0.1.16
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.
- package/README.md +2 -2
- package/dist/elements/auth-styles.d.ts +1 -1
- package/dist/elements/auth-styles.d.ts.map +1 -1
- package/dist/elements/auth-styles.js +21 -4
- package/dist/elements/auth-styles.js.map +1 -1
- package/dist/elements/minca-auth.d.ts.map +1 -1
- package/dist/elements/minca-auth.js +151 -57
- package/dist/elements/minca-auth.js.map +1 -1
- package/dist/identity/abilities.d.ts +2 -0
- package/dist/identity/abilities.d.ts.map +1 -1
- package/dist/identity/abilities.js +2 -0
- package/dist/identity/abilities.js.map +1 -1
- package/dist/identity/account-vault.d.ts +15 -71
- package/dist/identity/account-vault.d.ts.map +1 -1
- package/dist/identity/account-vault.js +45 -104
- package/dist/identity/account-vault.js.map +1 -1
- package/dist/identity/channel.d.ts +3 -9
- package/dist/identity/channel.d.ts.map +1 -1
- package/dist/identity/channel.js +42 -42
- package/dist/identity/channel.js.map +1 -1
- package/dist/identity/contact-key.d.ts +14 -29
- package/dist/identity/contact-key.d.ts.map +1 -1
- package/dist/identity/contact-key.js +31 -51
- package/dist/identity/contact-key.js.map +1 -1
- package/dist/identity/crypto-p256.d.ts.map +1 -1
- package/dist/identity/crypto-p256.js +39 -53
- package/dist/identity/crypto-p256.js.map +1 -1
- package/dist/identity/hpke.d.ts.map +1 -1
- package/dist/identity/hpke.js +19 -19
- package/dist/identity/hpke.js.map +1 -1
- package/dist/identity/identity-manager.d.ts.map +1 -1
- package/dist/identity/identity-manager.js +1 -2
- package/dist/identity/identity-manager.js.map +1 -1
- package/dist/identity/policy.d.ts.map +1 -1
- package/dist/identity/policy.js +35 -61
- package/dist/identity/policy.js.map +1 -1
- package/dist/identity/recovery-code.d.ts +2 -8
- package/dist/identity/recovery-code.d.ts.map +1 -1
- package/dist/identity/recovery-code.js +4 -11
- package/dist/identity/recovery-code.js.map +1 -1
- package/dist/identity/root-signer.d.ts +1 -6
- package/dist/identity/root-signer.d.ts.map +1 -1
- package/dist/identity/root-signer.js +12 -15
- package/dist/identity/root-signer.js.map +1 -1
- package/dist/identity/ucan.d.ts.map +1 -1
- package/dist/identity/ucan.js +48 -39
- package/dist/identity/ucan.js.map +1 -1
- package/dist/identity/webauthn.d.ts +6 -11
- package/dist/identity/webauthn.d.ts.map +1 -1
- package/dist/identity/webauthn.js +18 -30
- package/dist/identity/webauthn.js.map +1 -1
- package/dist/inbox/inbox.d.ts.map +1 -1
- package/dist/inbox/inbox.js +40 -30
- package/dist/inbox/inbox.js.map +1 -1
- package/dist/inbox/index.d.ts +2 -0
- package/dist/inbox/index.d.ts.map +1 -1
- package/dist/inbox/index.js +1 -0
- package/dist/inbox/index.js.map +1 -1
- package/dist/inbox/names.d.ts +54 -0
- package/dist/inbox/names.d.ts.map +1 -0
- package/dist/inbox/names.js +299 -0
- package/dist/inbox/names.js.map +1 -0
- package/dist/index.d.ts +3 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -12
- package/dist/index.js.map +1 -1
- package/dist/network/mesh.d.ts +7 -20
- package/dist/network/mesh.d.ts.map +1 -1
- package/dist/network/mesh.js +267 -245
- package/dist/network/mesh.js.map +1 -1
- package/dist/network/relay-link.d.ts +31 -0
- package/dist/network/relay-link.d.ts.map +1 -0
- package/dist/network/relay-link.js +62 -0
- package/dist/network/relay-link.js.map +1 -0
- package/dist/network/relay-minca.d.ts.map +1 -1
- package/dist/network/relay-minca.js +11 -49
- package/dist/network/relay-minca.js.map +1 -1
- package/dist/network/relay-nostr.d.ts.map +1 -1
- package/dist/network/relay-nostr.js +23 -63
- package/dist/network/relay-nostr.js.map +1 -1
- package/dist/network/relay-socket.d.ts +1 -1
- package/dist/network/relay-socket.d.ts.map +1 -1
- package/dist/network/relay-socket.js +3 -1
- package/dist/network/relay-socket.js.map +1 -1
- package/dist/node/actions.d.ts.map +1 -1
- package/dist/node/actions.js +50 -38
- package/dist/node/actions.js.map +1 -1
- package/dist/node/api.d.ts +6 -0
- package/dist/node/api.d.ts.map +1 -1
- package/dist/node/api.js +6 -0
- package/dist/node/api.js.map +1 -1
- package/dist/node/carrier.d.ts +5 -0
- package/dist/node/carrier.d.ts.map +1 -1
- package/dist/node/carrier.js +94 -73
- package/dist/node/carrier.js.map +1 -1
- package/dist/node/copy.d.ts +8 -7
- package/dist/node/copy.d.ts.map +1 -1
- package/dist/node/copy.js +54 -56
- package/dist/node/copy.js.map +1 -1
- package/dist/node/host.d.ts +39 -65
- package/dist/node/host.d.ts.map +1 -1
- package/dist/node/host.js +362 -379
- package/dist/node/host.js.map +1 -1
- package/dist/node/index.d.ts +2 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/node-carriers.d.ts +35 -0
- package/dist/node/node-carriers.d.ts.map +1 -0
- package/dist/node/node-carriers.js +562 -0
- package/dist/node/node-carriers.js.map +1 -0
- package/dist/node/node-contacts.d.ts +11 -0
- package/dist/node/node-contacts.d.ts.map +1 -0
- package/dist/node/node-contacts.js +808 -0
- package/dist/node/node-contacts.js.map +1 -0
- package/dist/node/node-context.d.ts +76 -0
- package/dist/node/node-context.d.ts.map +1 -0
- package/dist/node/node-context.js +54 -0
- package/dist/node/node-context.js.map +1 -0
- package/dist/node/node-hosting.d.ts +20 -0
- package/dist/node/node-hosting.d.ts.map +1 -0
- package/dist/node/node-hosting.js +449 -0
- package/dist/node/node-hosting.js.map +1 -0
- package/dist/node/node-records.d.ts +18 -0
- package/dist/node/node-records.d.ts.map +1 -0
- package/dist/node/node-records.js +262 -0
- package/dist/node/node-records.js.map +1 -0
- package/dist/node/node.d.ts.map +1 -1
- package/dist/node/node.js +198 -1990
- package/dist/node/node.js.map +1 -1
- package/dist/node/remote.d.ts +5 -6
- package/dist/node/remote.d.ts.map +1 -1
- package/dist/node/remote.js +272 -260
- package/dist/node/remote.js.map +1 -1
- package/dist/node/space-catalog.d.ts +40 -0
- package/dist/node/space-catalog.d.ts.map +1 -0
- package/dist/node/space-catalog.js +158 -0
- package/dist/node/space-catalog.js.map +1 -0
- package/dist/node/space-checks.d.ts +25 -0
- package/dist/node/space-checks.d.ts.map +1 -0
- package/dist/node/space-checks.js +343 -0
- package/dist/node/space-checks.js.map +1 -0
- package/dist/node/space-history.d.ts +37 -0
- package/dist/node/space-history.d.ts.map +1 -0
- package/dist/node/space-history.js +350 -0
- package/dist/node/space-history.js.map +1 -0
- package/dist/node/space-holding.d.ts +49 -0
- package/dist/node/space-holding.d.ts.map +1 -0
- package/dist/node/space-holding.js +267 -0
- package/dist/node/space-holding.js.map +1 -0
- package/dist/node/space-index.d.ts +41 -0
- package/dist/node/space-index.d.ts.map +1 -0
- package/dist/node/space-index.js +217 -0
- package/dist/node/space-index.js.map +1 -0
- package/dist/node/space-keys.d.ts +34 -0
- package/dist/node/space-keys.d.ts.map +1 -0
- package/dist/node/space-keys.js +309 -0
- package/dist/node/space-keys.js.map +1 -0
- package/dist/node/space-lines.d.ts +33 -0
- package/dist/node/space-lines.d.ts.map +1 -0
- package/dist/node/space-lines.js +145 -0
- package/dist/node/space-lines.js.map +1 -0
- package/dist/node/space-membership.d.ts +69 -0
- package/dist/node/space-membership.d.ts.map +1 -0
- package/dist/node/space-membership.js +242 -0
- package/dist/node/space-membership.js.map +1 -0
- package/dist/node/space-mirrors.d.ts +43 -0
- package/dist/node/space-mirrors.d.ts.map +1 -0
- package/dist/node/space-mirrors.js +125 -0
- package/dist/node/space-mirrors.js.map +1 -0
- package/dist/node/space-peers.d.ts +104 -0
- package/dist/node/space-peers.d.ts.map +1 -0
- package/dist/node/space-peers.js +595 -0
- package/dist/node/space-peers.js.map +1 -0
- package/dist/node/space-profiles.d.ts +18 -0
- package/dist/node/space-profiles.d.ts.map +1 -0
- package/dist/node/space-profiles.js +105 -0
- package/dist/node/space-profiles.js.map +1 -0
- package/dist/node/space-rules.d.ts +29 -0
- package/dist/node/space-rules.d.ts.map +1 -0
- package/dist/node/space-rules.js +144 -0
- package/dist/node/space-rules.js.map +1 -0
- package/dist/node/space-runtime.d.ts +103 -142
- package/dist/node/space-runtime.d.ts.map +1 -1
- package/dist/node/space-runtime.js +290 -3963
- package/dist/node/space-runtime.js.map +1 -1
- package/dist/node/space-standing.d.ts +20 -0
- package/dist/node/space-standing.d.ts.map +1 -0
- package/dist/node/space-standing.js +317 -0
- package/dist/node/space-standing.js.map +1 -0
- package/dist/node/space-versions.d.ts +104 -0
- package/dist/node/space-versions.d.ts.map +1 -0
- package/dist/node/space-versions.js +153 -0
- package/dist/node/space-versions.js.map +1 -0
- package/dist/node/space-warrants.d.ts +25 -0
- package/dist/node/space-warrants.d.ts.map +1 -0
- package/dist/node/space-warrants.js +214 -0
- package/dist/node/space-warrants.js.map +1 -0
- package/dist/node/space-writing.d.ts +72 -0
- package/dist/node/space-writing.d.ts.map +1 -0
- package/dist/node/space-writing.js +440 -0
- package/dist/node/space-writing.js.map +1 -0
- package/dist/node/stores.d.ts +19 -50
- package/dist/node/stores.d.ts.map +1 -1
- package/dist/node/stores.js +14 -33
- package/dist/node/stores.js.map +1 -1
- package/dist/node/types.d.ts +225 -306
- package/dist/node/types.d.ts.map +1 -1
- package/dist/node/usage.d.ts +2 -24
- package/dist/node/usage.d.ts.map +1 -1
- package/dist/node/usage.js +118 -102
- package/dist/node/usage.js.map +1 -1
- package/dist/node/watch-notifications.d.ts.map +1 -1
- package/dist/node/watch-notifications.js +32 -29
- package/dist/node/watch-notifications.js.map +1 -1
- package/dist/node/worker.d.ts +5 -6
- package/dist/node/worker.d.ts.map +1 -1
- package/dist/node/worker.js +80 -72
- package/dist/node/worker.js.map +1 -1
- package/dist/node/writer-keys.d.ts +5 -6
- package/dist/node/writer-keys.d.ts.map +1 -1
- package/dist/node/writer-keys.js +66 -57
- package/dist/node/writer-keys.js.map +1 -1
- package/dist/node/writers.d.ts +12 -19
- package/dist/node/writers.d.ts.map +1 -1
- package/dist/node/writers.js +7 -15
- package/dist/node/writers.js.map +1 -1
- package/dist/privacy/direct.d.ts.map +1 -1
- package/dist/privacy/direct.js +31 -27
- package/dist/privacy/direct.js.map +1 -1
- package/dist/privacy/space-encryption.d.ts.map +1 -1
- package/dist/privacy/space-encryption.js +5 -9
- package/dist/privacy/space-encryption.js.map +1 -1
- package/dist/query/computed.d.ts.map +1 -1
- package/dist/query/computed.js +78 -77
- package/dist/query/computed.js.map +1 -1
- package/dist/query/engine.d.ts +3 -4
- package/dist/query/engine.d.ts.map +1 -1
- package/dist/query/engine.js +93 -86
- package/dist/query/engine.js.map +1 -1
- package/dist/query/filter.d.ts +8 -10
- package/dist/query/filter.d.ts.map +1 -1
- package/dist/query/filter.js +144 -161
- package/dist/query/filter.js.map +1 -1
- package/dist/records/cel-types.d.ts.map +1 -1
- package/dist/records/cel-types.js +13 -27
- package/dist/records/cel-types.js.map +1 -1
- package/dist/records/cel.d.ts.map +1 -1
- package/dist/records/cel.js +177 -242
- package/dist/records/cel.js.map +1 -1
- package/dist/records/rules.d.ts.map +1 -1
- package/dist/records/rules.js +46 -50
- package/dist/records/rules.js.map +1 -1
- package/dist/records/topics.d.ts.map +1 -1
- package/dist/records/topics.js +18 -22
- package/dist/records/topics.js.map +1 -1
- package/dist/schemas/automations.d.ts +8 -15
- package/dist/schemas/automations.d.ts.map +1 -1
- package/dist/schemas/automations.js +203 -165
- package/dist/schemas/automations.js.map +1 -1
- package/dist/schemas/blueprints.d.ts.map +1 -1
- package/dist/schemas/blueprints.js +14 -13
- package/dist/schemas/blueprints.js.map +1 -1
- package/dist/schemas/connectors.d.ts.map +1 -1
- package/dist/schemas/connectors.js +16 -11
- package/dist/schemas/connectors.js.map +1 -1
- package/dist/schemas/contacts.d.ts +57 -0
- package/dist/schemas/contacts.d.ts.map +1 -1
- package/dist/schemas/contacts.js +32 -0
- package/dist/schemas/contacts.js.map +1 -1
- package/dist/schemas/cron.d.ts.map +1 -1
- package/dist/schemas/cron.js +27 -28
- package/dist/schemas/cron.js.map +1 -1
- package/dist/schemas/defined.d.ts +6 -0
- package/dist/schemas/defined.d.ts.map +1 -0
- package/dist/schemas/defined.js +7 -0
- package/dist/schemas/defined.js.map +1 -0
- package/dist/schemas/guides.d.ts +3 -1
- package/dist/schemas/guides.d.ts.map +1 -1
- package/dist/schemas/guides.js +13 -12
- package/dist/schemas/guides.js.map +1 -1
- package/dist/schemas/index.d.ts +2 -2
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +18 -14
- package/dist/schemas/index.js.map +1 -1
- package/dist/session/account-hint.d.ts.map +1 -1
- package/dist/session/account-hint.js +8 -5
- package/dist/session/account-hint.js.map +1 -1
- package/dist/session/auth.d.ts +36 -2
- package/dist/session/auth.d.ts.map +1 -1
- package/dist/session/auth.js +95 -2
- package/dist/session/auth.js.map +1 -1
- package/dist/session/connect.d.ts +1 -0
- package/dist/session/connect.d.ts.map +1 -1
- package/dist/session/connect.js +3 -1
- package/dist/session/connect.js.map +1 -1
- package/dist/session/credentials.d.ts +8 -26
- package/dist/session/credentials.d.ts.map +1 -1
- package/dist/session/credentials.js +14 -32
- package/dist/session/credentials.js.map +1 -1
- package/dist/session/index.d.ts +1 -0
- package/dist/session/index.d.ts.map +1 -1
- package/dist/session/index.js +1 -0
- package/dist/session/index.js.map +1 -1
- package/dist/session/pairing.d.ts.map +1 -1
- package/dist/session/pairing.js +92 -88
- package/dist/session/pairing.js.map +1 -1
- package/dist/session/password-strength.d.ts.map +1 -1
- package/dist/session/password-strength.js +37 -37
- package/dist/session/password-strength.js.map +1 -1
- package/dist/session/places.d.ts.map +1 -1
- package/dist/session/places.js +18 -13
- package/dist/session/places.js.map +1 -1
- package/dist/session/popup.d.ts +13 -0
- package/dist/session/popup.d.ts.map +1 -0
- package/dist/session/popup.js +23 -0
- package/dist/session/popup.js.map +1 -0
- package/dist/space/constitution.d.ts.map +1 -1
- package/dist/space/constitution.js +22 -29
- package/dist/space/constitution.js.map +1 -1
- package/dist/space/grants.d.ts.map +1 -1
- package/dist/space/grants.js +37 -39
- package/dist/space/grants.js.map +1 -1
- package/dist/space/invite-link.d.ts.map +1 -1
- package/dist/space/invite-link.js +33 -33
- package/dist/space/invite-link.js.map +1 -1
- package/dist/space/own-automations.d.ts +13 -24
- package/dist/space/own-automations.d.ts.map +1 -1
- package/dist/space/own-automations.js +47 -37
- package/dist/space/own-automations.js.map +1 -1
- package/dist/space/roles.d.ts +56 -80
- package/dist/space/roles.d.ts.map +1 -1
- package/dist/space/roles.js +448 -441
- package/dist/space/roles.js.map +1 -1
- package/dist/space/space-access.d.ts +3 -4
- package/dist/space/space-access.d.ts.map +1 -1
- package/dist/space/space-access.js +3 -8
- package/dist/space/space-access.js.map +1 -1
- package/dist/storage/blob/directory.d.ts.map +1 -1
- package/dist/storage/blob/directory.js +39 -32
- package/dist/storage/blob/directory.js.map +1 -1
- package/dist/storage/blob/s3.d.ts.map +1 -1
- package/dist/storage/blob/s3.js +21 -19
- package/dist/storage/blob/s3.js.map +1 -1
- package/dist/storage/blob-store.d.ts +0 -9
- package/dist/storage/blob-store.d.ts.map +1 -1
- package/dist/storage/directory-access.d.ts +8 -32
- package/dist/storage/directory-access.d.ts.map +1 -1
- package/dist/storage/directory-access.js +11 -36
- package/dist/storage/directory-access.js.map +1 -1
- package/dist/storage/encrypted-adapter.d.ts +12 -32
- package/dist/storage/encrypted-adapter.d.ts.map +1 -1
- package/dist/storage/encrypted-adapter.js +31 -54
- package/dist/storage/encrypted-adapter.js.map +1 -1
- package/dist/storage/folder-adapter.d.ts +12 -26
- package/dist/storage/folder-adapter.d.ts.map +1 -1
- package/dist/storage/folder-adapter.js +37 -54
- package/dist/storage/folder-adapter.js.map +1 -1
- package/dist/storage/folder-reconcile.d.ts +12 -26
- package/dist/storage/folder-reconcile.d.ts.map +1 -1
- package/dist/storage/folder-reconcile.js +39 -48
- package/dist/storage/folder-reconcile.js.map +1 -1
- package/dist/storage/indexeddb-adapter.d.ts +2 -6
- package/dist/storage/indexeddb-adapter.d.ts.map +1 -1
- package/dist/storage/indexeddb-adapter.js +60 -114
- package/dist/storage/indexeddb-adapter.js.map +1 -1
- package/dist/storage/mirror.d.ts +0 -29
- package/dist/storage/mirror.d.ts.map +1 -1
- package/dist/storage/mirror.js +153 -110
- package/dist/storage/mirror.js.map +1 -1
- package/dist/storage/segment.d.ts.map +1 -1
- package/dist/storage/segment.js +3 -7
- package/dist/storage/segment.js.map +1 -1
- package/dist/storage/storage-provider.d.ts +6 -11
- package/dist/storage/storage-provider.d.ts.map +1 -1
- package/dist/storage/storage-provider.js +112 -116
- package/dist/storage/storage-provider.js.map +1 -1
- package/dist/sync/sync-engine.d.ts +10 -44
- package/dist/sync/sync-engine.d.ts.map +1 -1
- package/dist/sync/sync-engine.js +245 -247
- package/dist/sync/sync-engine.js.map +1 -1
- package/dist/sync/sync-messages.d.ts +1 -1
- package/dist/sync/sync-messages.d.ts.map +1 -1
- package/dist/sync/sync-messages.js +1 -1
- package/dist/sync/sync-messages.js.map +1 -1
- package/dist/utils/guards.d.ts +1 -0
- package/dist/utils/guards.d.ts.map +1 -1
- package/dist/utils/guards.js +1 -0
- package/dist/utils/guards.js.map +1 -1
- package/dist/utils/hmac.d.ts +5 -0
- package/dist/utils/hmac.d.ts.map +1 -0
- package/dist/utils/hmac.js +20 -0
- package/dist/utils/hmac.js.map +1 -0
- package/dist/utils/map.d.ts +10 -0
- package/dist/utils/map.d.ts.map +1 -0
- package/dist/utils/map.js +30 -0
- package/dist/utils/map.js.map +1 -0
- package/dist/utils/serial.d.ts +2 -0
- package/dist/utils/serial.d.ts.map +1 -1
- package/dist/utils/serial.js +9 -0
- package/dist/utils/serial.js.map +1 -1
- package/dist/validation/capability-gate.d.ts +7 -15
- package/dist/validation/capability-gate.d.ts.map +1 -1
- package/dist/validation/capability-gate.js +32 -36
- package/dist/validation/capability-gate.js.map +1 -1
- package/dist/validation/crypto-gate.d.ts.map +1 -1
- package/dist/validation/crypto-gate.js +12 -21
- package/dist/validation/crypto-gate.js.map +1 -1
- package/docs/README.md +1 -0
- package/docs/actions.md +1 -1
- package/docs/automations.md +1 -1
- package/docs/blueprints-and-guides.md +17 -1
- package/docs/building-an-app.md +7 -4
- package/docs/collections.md +3 -3
- package/docs/contacts.md +34 -1
- package/docs/contracts.md +1 -1
- package/docs/direct-messages.md +1 -1
- package/docs/inbox.md +5 -11
- package/docs/node.md +22 -14
- package/docs/records-and-queries.md +1 -1
- package/docs/sign-in.md +54 -26
- package/docs/spaces.md +6 -6
- package/docs/standard-library.md +7 -6
- package/docs/storage.md +4 -5
- package/docs/usernames.md +161 -0
- package/docs/warrants.md +1 -1
- package/package.json +1 -1
package/dist/node/node.js
CHANGED
|
@@ -6,43 +6,37 @@
|
|
|
6
6
|
* **The root key signs once.** A node signs with a session key the root
|
|
7
7
|
* delegates to for an hour at a time, renewed before it runs out: one
|
|
8
8
|
* signature an hour, never one per write.
|
|
9
|
+
*
|
|
10
|
+
* This file owns the session, the spaces the node holds and the account's
|
|
11
|
+
* memberships; each other part lives in a `node-*.ts` file beside it and is
|
|
12
|
+
* wired together here, sharing one `NodeContext`.
|
|
9
13
|
*/
|
|
10
|
-
import { runQuery } from '../query/engine.js';
|
|
11
|
-
import { nameOf, plainQuery, } from '../query/types.js';
|
|
12
14
|
import { createP256Provider } from '../identity/crypto-p256.js';
|
|
13
15
|
import { didOf } from '../identity/did.js';
|
|
14
|
-
import {
|
|
15
|
-
import { actsForAccount, ALL_COMMAND, grantsRecordsOnly, noteSpaces } from '../identity/abilities.js';
|
|
16
|
+
import { actsForAccount, ALL_COMMAND } from '../identity/abilities.js';
|
|
16
17
|
import { createSigner } from '../schema/signer.js';
|
|
17
18
|
import { createSchemaEngine } from '../schema/schema-engine.js';
|
|
18
|
-
import { createSpaceManager, encodeSpaceInvite, parseSpaceInvite,
|
|
19
|
-
import {
|
|
20
|
-
import { KEY_CHANGE, MEMBER_REMOVE, ROLE_ASSIGN, SPACE_KEEPERS } from '../space/grants.js';
|
|
19
|
+
import { createSpaceManager, encodeSpaceInvite, parseSpaceInvite, previewInvite, } from '../space/space-manager.js';
|
|
20
|
+
import { ROLE_ASSIGN } from '../space/grants.js';
|
|
21
21
|
import { createWriters } from './writers.js';
|
|
22
|
-
import {
|
|
22
|
+
import { openSpaceRuntime } from './space-runtime.js';
|
|
23
|
+
import { meshFor } from './space-peers.js';
|
|
23
24
|
import { createServerAuth } from '../network/peer-auth.js';
|
|
24
25
|
import { DEFAULT_ICE_SERVERS } from '../network/rtc-transport.js';
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import { checkInvitation, readInvitation, writeInvitation } from '../space/invitation.js';
|
|
26
|
+
import { generateLinkSecret, linkInviteSecret } from '../space/invite-link.js';
|
|
27
|
+
import { checkInvitation } from '../space/invitation.js';
|
|
28
28
|
import { foundersOf } from '../space/constitution.js';
|
|
29
|
-
import {
|
|
30
|
-
import { isRecord, unref } from '../utils/guards.js';
|
|
29
|
+
import { unref } from '../utils/guards.js';
|
|
31
30
|
import { createListeners } from '../utils/events.js';
|
|
32
31
|
import { serial } from '../utils/serial.js';
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
40
|
-
import {
|
|
41
|
-
import { CARRIER_COLLECTION, isKeptLink, LINK_COLLECTION, deriveAccountRegistry, deriveCarrySpace, deriveContactsSpace, MEMBERSHIP_COLLECTION, PROFILE_COLLECTION, PROFILE_KEY, isAvatarRef, } from '../space/account-registry.js';
|
|
42
|
-
import { CARRY_CLOSED_KEY, makePass, PASS_COLLECTION, passKey } from '../space/pass.js';
|
|
43
|
-
import { checkOwnAutomation, OWN_AUTOMATIONS, WAKE_COLLECTION, linkedWakes, wakeFor, } from '../space/own-automations.js';
|
|
44
|
-
import { createHostClient, connectorOffers, createSpaceHostClient, describeHost, hostPeerAddress, HOSTING_COLLECTION, HostError, newSubscriptionSeed, readStatus, subscriptionKey, } from '../session/hosting.js';
|
|
45
|
-
import { base32Encode, hashedKey } from '../utils/hash.js';
|
|
32
|
+
import { contactKeyPair, deriveMemberKeyBytes } from '../identity/contact-key.js';
|
|
33
|
+
import { createMailboxClient } from '../network/relays.js';
|
|
34
|
+
import { deriveAccountRegistry, deriveContactsSpace, MEMBERSHIP_COLLECTION, } from '../space/account-registry.js';
|
|
35
|
+
import { inBackground } from './node-context.js';
|
|
36
|
+
import { createNodeCarriers } from './node-carriers.js';
|
|
37
|
+
import { createNodeHosting } from './node-hosting.js';
|
|
38
|
+
import { createNodeContacts } from './node-contacts.js';
|
|
39
|
+
import { createNodeDirect, createNodeRecords, startAgent } from './node-records.js';
|
|
46
40
|
/** Everything a session key may do: every command, about the whole account */
|
|
47
41
|
export const SESSION_COMMAND = ALL_COMMAND;
|
|
48
42
|
const DEFAULT_TTL_SECONDS = 3600;
|
|
@@ -65,26 +59,6 @@ function summarize(record) {
|
|
|
65
59
|
joining: record.invite !== null,
|
|
66
60
|
});
|
|
67
61
|
}
|
|
68
|
-
/** Every collection a query reads: its own, and each `include … from` */
|
|
69
|
-
function collectionsOf(query) {
|
|
70
|
-
const plain = plainQuery(query);
|
|
71
|
-
const found = new Set();
|
|
72
|
-
if (typeof plain.collection === 'string')
|
|
73
|
-
found.add(plain.collection);
|
|
74
|
-
const walk = (includes) => {
|
|
75
|
-
for (const include of Object.values(includes ?? {})) {
|
|
76
|
-
if (typeof include?.from === 'string')
|
|
77
|
-
found.add(include.from);
|
|
78
|
-
walk(include?.include);
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
walk(plain.include);
|
|
82
|
-
return [...found];
|
|
83
|
-
}
|
|
84
|
-
/** What a rejection says: its message when it has one */
|
|
85
|
-
function reasonText(reason) {
|
|
86
|
-
return String((isRecord(reason) ? reason.message : undefined) ?? reason);
|
|
87
|
-
}
|
|
88
62
|
/** Starts a node; call `close()` when done */
|
|
89
63
|
export async function createNode(config) {
|
|
90
64
|
const provider = config.provider ?? createP256Provider();
|
|
@@ -106,31 +80,29 @@ export async function createNode(config) {
|
|
|
106
80
|
let current = await delegate();
|
|
107
81
|
let closed = false;
|
|
108
82
|
let renewTimer = null;
|
|
109
|
-
|
|
110
|
-
renewTimer = setTimeout(() =>
|
|
111
|
-
delegate()
|
|
112
|
-
.then((token) => {
|
|
113
|
-
current = token;
|
|
114
|
-
scheduleRenewal(ttl * 0.75);
|
|
115
|
-
})
|
|
116
|
-
.catch(() => {
|
|
117
|
-
// The signer said no or was unreachable. Keep the delegation we have
|
|
118
|
-
// and ask again soon; writes fail validation once it expires.
|
|
119
|
-
if (!closed)
|
|
120
|
-
scheduleRenewal(Math.min(60, ttl / 4));
|
|
121
|
-
});
|
|
122
|
-
}, inSeconds * 1000);
|
|
83
|
+
function scheduleRenewal(inSeconds) {
|
|
84
|
+
renewTimer = setTimeout(() => void renew(), inSeconds * 1000);
|
|
123
85
|
unref(renewTimer);
|
|
124
|
-
}
|
|
86
|
+
}
|
|
87
|
+
async function renew() {
|
|
88
|
+
try {
|
|
89
|
+
current = await delegate();
|
|
90
|
+
scheduleRenewal(ttl * 0.75);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Keep the delegation we have and ask again soon; writes fail once it expires.
|
|
94
|
+
if (!closed)
|
|
95
|
+
scheduleRenewal(Math.min(60, ttl / 4));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
125
98
|
scheduleRenewal(ttl * 0.75);
|
|
126
99
|
const session = {
|
|
127
100
|
did: sessionDid,
|
|
128
101
|
key: sessionKeys.privateKey,
|
|
129
102
|
proof: () => current,
|
|
130
103
|
};
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
// node's stores (`node/writers.ts`).
|
|
104
|
+
// Where a key keeps its places in each log: a claimed key in its slot, one handed in
|
|
105
|
+
// (an agent's, an app's) in the node's stores, and one made here nowhere.
|
|
134
106
|
const handedIn = await config.stores('writers');
|
|
135
107
|
const writers = createWriters((did) => did !== sessionDid ? handedIn : (claimed?.heads ?? (config.sessionKey ? handedIn : null)));
|
|
136
108
|
const mesh = meshFor(config.network, session);
|
|
@@ -175,57 +147,19 @@ export async function createNode(config) {
|
|
|
175
147
|
if (contactsRecord && !(await registry.get(contactsRecord.space.id))) {
|
|
176
148
|
await joinRegistry(await encodeSpaceInvite(contactsRecord, looseSigner(), provider));
|
|
177
149
|
}
|
|
178
|
-
/** Which of the account's own spaces this is, or null for one it uses */
|
|
179
150
|
async function kindOf(spaceId) {
|
|
180
151
|
if (spaceId === accountSpaceId)
|
|
181
152
|
return 'registry';
|
|
182
153
|
if (spaceId === contactsSpaceId)
|
|
183
154
|
return 'contacts';
|
|
184
|
-
return (await isCarrySpace(spaceId)) ? 'carry' : null;
|
|
155
|
+
return (await carrying.isCarrySpace(spaceId)) ? 'carry' : null;
|
|
185
156
|
}
|
|
186
|
-
/** The contact key, for a node allowed to open contact requests */
|
|
187
157
|
const contactKeys = config.contactKey ? await contactKeyPair(config.contactKey) : null;
|
|
188
|
-
/**
|
|
189
|
-
* An invite to a space, naming where its members meet: the relays the space
|
|
190
|
-
* names, or before it names any, this node's — so the joiner finds the
|
|
191
|
-
* inviter even when their app uses other relays.
|
|
192
|
-
*/
|
|
193
|
-
async function inviteTo(spaceId, options = {}) {
|
|
194
|
-
const named = (await findRecord(spaceId))?.relays ?? [];
|
|
195
|
-
const own = usableRelays(config.network).slice(0, MAX_RELAYS);
|
|
196
|
-
const nodes = await nodesOf(spaceId);
|
|
197
|
-
return registry.createInvite(spaceId, looseSigner(), {
|
|
198
|
-
...options,
|
|
199
|
-
...(named.length ? {} : own.length ? { relays: own } : {}),
|
|
200
|
-
...(nodes.length ? { nodes } : {}),
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* The always-on nodes an invite names, so a joiner reaches one with nobody
|
|
205
|
-
* else online: the account's hosts, the space's own, and those the invite
|
|
206
|
-
* that brought this node here named. A host that can't be described in a
|
|
207
|
-
* few seconds is left out rather than holding the invite up.
|
|
208
|
-
*/
|
|
209
|
-
async function nodesOf(spaceId) {
|
|
210
|
-
if (!config.network)
|
|
211
|
-
return [];
|
|
212
|
-
const hosts = [
|
|
213
|
-
...(await hostingRecords()),
|
|
214
|
-
...((await kindOf(spaceId)) ? [] : await namedHosts(spaceId).catch(() => [])),
|
|
215
|
-
];
|
|
216
|
-
const inTime = (peer) => Promise.race([peer, new Promise((resolve) => unref(setTimeout(() => resolve(null), 3000)))]);
|
|
217
|
-
// Not the nodes an invite gave this node: nothing vouches for them, so they are used here and never passed on.
|
|
218
|
-
const peers = await Promise.all(hosts.map((host) => inTime(peerOf(host).catch(() => null))));
|
|
219
|
-
const pinned = [
|
|
220
|
-
...new Set(peers.filter((peer) => peer !== null && peer.includes('#did:key:'))),
|
|
221
|
-
];
|
|
222
|
-
return pinned.slice(0, MAX_INVITE_NODES);
|
|
223
|
-
}
|
|
224
158
|
async function findRecord(spaceId) {
|
|
225
159
|
if (spaceId === accountSpaceId)
|
|
226
160
|
return account;
|
|
227
161
|
const held = await registry.get(spaceId);
|
|
228
|
-
return held ?? (await carrierRecords()).find(({ carry }) => carry.space.id === spaceId)?.carry ?? null;
|
|
162
|
+
return (held ?? (await carrying.carrierRecords()).find(({ carry }) => carry.space.id === spaceId)?.carry ?? null);
|
|
229
163
|
}
|
|
230
164
|
async function requireRecord(spaceId) {
|
|
231
165
|
const record = await findRecord(spaceId);
|
|
@@ -253,176 +187,103 @@ export async function createNode(config) {
|
|
|
253
187
|
}
|
|
254
188
|
if (event.type !== 'records')
|
|
255
189
|
return;
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
?.then((rt) => checkRevoked(event.space, rt))
|
|
259
|
-
.catch(() => { });
|
|
260
|
-
void keepSpaceHosts(event.space).catch(() => { });
|
|
190
|
+
whenOpen(event.space, checkRevoked);
|
|
191
|
+
inBackground(hosts.keepSpaceHosts(event.space));
|
|
261
192
|
// A space joined with an invite whose record had not arrived: perhaps it has now.
|
|
262
193
|
void finishJoining(event.space);
|
|
263
194
|
if (event.space === accountSpaceId) {
|
|
264
195
|
emit({ type: 'account' });
|
|
265
196
|
void reconcile();
|
|
266
197
|
// A rename on another device reaches the spaces open here too.
|
|
267
|
-
void publishProfileToOpenSpaces();
|
|
198
|
+
void people.publishProfileToOpenSpaces();
|
|
268
199
|
}
|
|
269
200
|
};
|
|
270
|
-
/** The account registry, or why `what` can't be done without it */
|
|
271
201
|
function requireAccount(what) {
|
|
272
202
|
if (!accountSpaceId)
|
|
273
203
|
return Promise.reject(new Error(`${what} needs the account key`));
|
|
274
204
|
return runtime(accountSpaceId);
|
|
275
205
|
}
|
|
276
|
-
/** What this account wrote in a collection that `check` takes: only it writes its own lists */
|
|
277
206
|
async function ownRecords(rt, options, check = () => true) {
|
|
278
207
|
return (await rt.list(options)).filter((record) => record.verified && record.root === config.signer.did && check(record));
|
|
279
208
|
}
|
|
280
|
-
|
|
281
|
-
* The account's profile, from its registry — null without an account key,
|
|
282
|
-
* or before one is set. One record: its current version is the name, by the
|
|
283
|
-
* ordering rule, the same on every device whatever their clocks say.
|
|
284
|
-
*/
|
|
285
|
-
async function ownProfile() {
|
|
209
|
+
async function accountRecords(options, check) {
|
|
286
210
|
if (!accountSpaceId)
|
|
287
|
-
return
|
|
288
|
-
|
|
289
|
-
if (!profile?.verified || profile.root !== config.signer.did || typeof profile.body?.name !== 'string')
|
|
290
|
-
return null;
|
|
291
|
-
const avatar = profile.body.avatar;
|
|
292
|
-
return {
|
|
293
|
-
name: profile.body.name,
|
|
294
|
-
updatedAt: profile.updatedAt,
|
|
295
|
-
...(isAvatarRef(avatar) ? { avatar } : {}),
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
const ownName = async () => (await ownProfile())?.name ?? null;
|
|
299
|
-
/**
|
|
300
|
-
* Tells a space who this account is. Done when the space opens and when the
|
|
301
|
-
* name changes — not by opening every space, which would start syncing them
|
|
302
|
-
* all; a space not open now hears on its next open.
|
|
303
|
-
*/
|
|
304
|
-
async function publishProfile(spaceId, open) {
|
|
305
|
-
if (narrowNote || (await kindOf(spaceId)))
|
|
306
|
-
return;
|
|
307
|
-
const own = await ownProfile();
|
|
308
|
-
if (!own)
|
|
309
|
-
return;
|
|
310
|
-
const base = { name: own.name, ...(contactKeys ? { contactKey: contactKeys.publicKey } : {}) };
|
|
311
|
-
const held = (await open.profiles()).find((profile) => profile.did === config.signer.did)?.avatar;
|
|
312
|
-
const current = isAvatarRef(held) && held.source === own.avatar?.hash ? held : undefined;
|
|
313
|
-
// The name and contact key go out now, with the picture the space already has; a new picture
|
|
314
|
-
// follows once it is copied, which may wait on its bytes reaching this device.
|
|
315
|
-
const shown = own.avatar ? (current ?? (isAvatarRef(held) ? held : undefined)) : undefined;
|
|
316
|
-
await open.publishProfile({ ...base, ...(shown ? { avatar: shown } : {}) });
|
|
317
|
-
if (own.avatar && !current)
|
|
318
|
-
void avatarIn(spaceId, open, own.avatar)
|
|
319
|
-
.then((avatar) => open.publishProfile({ ...base, avatar }))
|
|
320
|
-
.catch(() => {
|
|
321
|
-
// Its bytes are on a device that is away: copied next time the profile is published.
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* The account's picture as a file of this space: a space's members can't
|
|
326
|
-
* read the registry, so each space holds its own copy, made once and named
|
|
327
|
-
* by the registry file it copies.
|
|
328
|
-
*/
|
|
329
|
-
function avatarIn(spaceId, open, avatar) {
|
|
330
|
-
// One copy per space and picture, however many publishes ask at once (a space opening, a change).
|
|
331
|
-
const at = `${spaceId}:${avatar.hash}`;
|
|
332
|
-
let copying = avatarCopies.get(at);
|
|
333
|
-
if (!copying) {
|
|
334
|
-
copying = (async () => {
|
|
335
|
-
const held = (await open.profiles()).find((profile) => profile.did === config.signer.did)?.avatar;
|
|
336
|
-
if (isAvatarRef(held) && held.source === avatar.hash)
|
|
337
|
-
return held;
|
|
338
|
-
const registryRt = await runtime(accountSpaceId);
|
|
339
|
-
const copy = await open.addFile(await registryRt.readFile(avatar));
|
|
340
|
-
return { ...copy, mime: avatar.mime, source: avatar.hash };
|
|
341
|
-
})();
|
|
342
|
-
copying.catch(() => avatarCopies.delete(at));
|
|
343
|
-
avatarCopies.set(at, copying);
|
|
344
|
-
}
|
|
345
|
-
return copying;
|
|
346
|
-
}
|
|
347
|
-
const avatarCopies = new Map();
|
|
348
|
-
async function publishProfileToOpenSpaces() {
|
|
349
|
-
for (const [spaceId, open] of runtimes) {
|
|
350
|
-
await open.then((rt) => publishProfile(spaceId, rt)).catch(() => { });
|
|
351
|
-
}
|
|
211
|
+
return [];
|
|
212
|
+
return ownRecords(await runtime(accountSpaceId), options, check);
|
|
352
213
|
}
|
|
353
214
|
function runtime(spaceId) {
|
|
354
215
|
if (closed)
|
|
355
216
|
return Promise.reject(new Error('Node is closed'));
|
|
356
|
-
|
|
357
|
-
if (
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
session,
|
|
368
|
-
rootDid: config.signer.did,
|
|
369
|
-
...(config.network ? { network: config.network } : {}),
|
|
370
|
-
...(mesh ? { mesh } : {}),
|
|
371
|
-
accountOnly: kind !== null,
|
|
372
|
-
// The account's own spaces are always held whole: every device needs all of them.
|
|
373
|
-
...(config.cache && !kind ? { cache: config.cache } : {}),
|
|
374
|
-
watchIntervalMs: config.watchIntervalMs ?? 2000,
|
|
375
|
-
...(config.fetchFiles ? { fetchFiles: config.fetchFiles } : {}),
|
|
376
|
-
emit: fromRuntime,
|
|
377
|
-
onRole: (role) => {
|
|
378
|
-
// Holding a role now — perhaps just joined — means the space may hear who this is.
|
|
379
|
-
if (role !== null)
|
|
380
|
-
void runtimes
|
|
381
|
-
.get(spaceId)
|
|
382
|
-
?.then((rt) => publishProfile(spaceId, rt))
|
|
383
|
-
.catch(() => { });
|
|
384
|
-
if (role !== null)
|
|
385
|
-
void keepSpaceHosts(spaceId).catch(() => { });
|
|
386
|
-
if (record.role === role)
|
|
387
|
-
return;
|
|
388
|
-
void registry.setRole(spaceId, role).then(() => emit({ type: 'spaces' }));
|
|
389
|
-
},
|
|
390
|
-
onJoined: () => {
|
|
391
|
-
if (!record.invite)
|
|
392
|
-
return;
|
|
393
|
-
void registry.clearInvite(spaceId).then(() => emit({ type: 'spaces' }));
|
|
394
|
-
},
|
|
395
|
-
memberKey: kind === 'registry'
|
|
396
|
-
? null
|
|
397
|
-
: config.accountKey
|
|
398
|
-
? await deriveMemberKeyBytes(config.accountKey, spaceId)
|
|
399
|
-
: (record.memberKey ?? null),
|
|
400
|
-
// Kept only for a space in the list: the registry is not in it.
|
|
401
|
-
onRelays: (relays) => registry.setRelays(spaceId, relays),
|
|
402
|
-
onKeys: async (keys, current) => {
|
|
403
|
-
if (kind === 'registry')
|
|
404
|
-
return;
|
|
405
|
-
await registry.addKeys(spaceId, keys, current);
|
|
406
|
-
// The account's other devices follow the new key, and its carriers: passes and wakes, not a whole reconcile.
|
|
407
|
-
if (!kind)
|
|
408
|
-
await remember(spaceId, { refresh: true });
|
|
409
|
-
void passAll().catch(() => { });
|
|
410
|
-
},
|
|
411
|
-
});
|
|
412
|
-
});
|
|
413
|
-
// A failed open must not be cached, or the space stays broken until restart.
|
|
414
|
-
open.catch(() => runtimes.delete(spaceId));
|
|
415
|
-
void open.then((rt) => publishProfile(spaceId, rt)).catch(() => { });
|
|
416
|
-
// A revoke that arrived on an earlier visit.
|
|
417
|
-
void open.then((rt) => checkRevoked(spaceId, rt)).catch(() => { });
|
|
418
|
-
// Carriers added since this space was last open.
|
|
419
|
-
void open.then((rt) => nameKeepers(spaceId, rt)).catch(() => { });
|
|
420
|
-
runtimes.set(spaceId, open);
|
|
421
|
-
// The hosts the account or the space uses, reached over their sockets.
|
|
422
|
-
void open.then(() => reachHosts(spaceId)).catch(() => { });
|
|
423
|
-
}
|
|
217
|
+
const known = runtimes.get(spaceId);
|
|
218
|
+
if (known)
|
|
219
|
+
return known;
|
|
220
|
+
const open = requireRecord(spaceId).then((record) => openRuntime(spaceId, record));
|
|
221
|
+
// A failed open is not kept, or the space would stay broken until restart.
|
|
222
|
+
open.catch(() => runtimes.delete(spaceId));
|
|
223
|
+
runtimes.set(spaceId, open);
|
|
224
|
+
// Its profile, a revoke from an earlier visit, carriers added since, and the hosts to reach.
|
|
225
|
+
for (const step of [people.publishProfile, checkRevoked, carrying.nameKeepers])
|
|
226
|
+
whenOpen(spaceId, step);
|
|
227
|
+
inBackground(open.then(() => hosts.reachHosts(spaceId)));
|
|
424
228
|
return open;
|
|
425
229
|
}
|
|
230
|
+
/** Runs `step` on a space's runtime in the background, if it is open */
|
|
231
|
+
function whenOpen(spaceId, step) {
|
|
232
|
+
const open = runtimes.get(spaceId);
|
|
233
|
+
if (open)
|
|
234
|
+
inBackground(open.then((rt) => step(spaceId, rt)));
|
|
235
|
+
}
|
|
236
|
+
async function openRuntime(spaceId, record) {
|
|
237
|
+
const kind = await kindOf(spaceId);
|
|
238
|
+
const memberKey = kind === 'registry' ? null : await memberKeyOf(spaceId, record);
|
|
239
|
+
return openSpaceRuntime({
|
|
240
|
+
record,
|
|
241
|
+
writers,
|
|
242
|
+
stores: config.stores,
|
|
243
|
+
provider,
|
|
244
|
+
signer,
|
|
245
|
+
schemas,
|
|
246
|
+
session,
|
|
247
|
+
rootDid: config.signer.did,
|
|
248
|
+
...(config.network ? { network: config.network } : {}),
|
|
249
|
+
...(mesh ? { mesh } : {}),
|
|
250
|
+
accountOnly: kind !== null,
|
|
251
|
+
// The account's own spaces are always held whole: every device needs all of them.
|
|
252
|
+
...(config.cache && !kind ? { cache: config.cache } : {}),
|
|
253
|
+
watchIntervalMs: config.watchIntervalMs ?? 2000,
|
|
254
|
+
...(config.fetchFiles ? { fetchFiles: config.fetchFiles } : {}),
|
|
255
|
+
emit: fromRuntime,
|
|
256
|
+
onRole: (role) => {
|
|
257
|
+
// Holding a role now, perhaps just joined: the space may hear who this is.
|
|
258
|
+
if (role !== null) {
|
|
259
|
+
whenOpen(spaceId, people.publishProfile);
|
|
260
|
+
inBackground(hosts.keepSpaceHosts(spaceId));
|
|
261
|
+
}
|
|
262
|
+
if (record.role !== role)
|
|
263
|
+
void registry.setRole(spaceId, role).then(() => emit({ type: 'spaces' }));
|
|
264
|
+
},
|
|
265
|
+
onJoined: () => {
|
|
266
|
+
if (record.invite)
|
|
267
|
+
void registry.clearInvite(spaceId).then(() => emit({ type: 'spaces' }));
|
|
268
|
+
},
|
|
269
|
+
memberKey,
|
|
270
|
+
onRelays: (relays) => registry.setRelays(spaceId, relays),
|
|
271
|
+
onKeys: async (keys, currentKey) => {
|
|
272
|
+
if (kind === 'registry')
|
|
273
|
+
return;
|
|
274
|
+
await registry.addKeys(spaceId, keys, currentKey);
|
|
275
|
+
// The account's other devices and its carriers follow the new key.
|
|
276
|
+
if (!kind)
|
|
277
|
+
await remember(spaceId, { refresh: true });
|
|
278
|
+
inBackground(carrying.passAll());
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
async function memberKeyOf(spaceId, record) {
|
|
283
|
+
if (!config.accountKey)
|
|
284
|
+
return record.memberKey ?? null;
|
|
285
|
+
return deriveMemberKeyBytes(config.accountKey, spaceId);
|
|
286
|
+
}
|
|
426
287
|
/** A method that opens the space its first argument names, and asks its runtime */
|
|
427
288
|
const perSpace = (call) => async (spaceId, ...args) => call(await runtime(spaceId), ...args);
|
|
428
289
|
/**
|
|
@@ -431,7 +292,6 @@ export async function createNode(config) {
|
|
|
431
292
|
* record that makes the difference may be the one that arrived meanwhile.
|
|
432
293
|
*/
|
|
433
294
|
const joining = new Map();
|
|
434
|
-
/** Takes in an invite; the space it is for may now have one waiting */
|
|
435
295
|
async function joinRegistry(invite) {
|
|
436
296
|
const record = await registry.join(invite);
|
|
437
297
|
noInviteWaiting.delete(record.space.id);
|
|
@@ -459,7 +319,7 @@ export async function createNode(config) {
|
|
|
459
319
|
}
|
|
460
320
|
async function closeRuntime(spaceId) {
|
|
461
321
|
holds.delete(spaceId);
|
|
462
|
-
|
|
322
|
+
hosts.forgetReach(spaceId);
|
|
463
323
|
const open = runtimes.get(spaceId);
|
|
464
324
|
if (!open)
|
|
465
325
|
return;
|
|
@@ -485,9 +345,7 @@ export async function createNode(config) {
|
|
|
485
345
|
}
|
|
486
346
|
};
|
|
487
347
|
async function memberships() {
|
|
488
|
-
|
|
489
|
-
return [];
|
|
490
|
-
return ownRecords(await runtime(accountSpaceId), { collection: MEMBERSHIP_COLLECTION, includeDeleted: true }, (record) => record.deleted ||
|
|
348
|
+
return accountRecords({ collection: MEMBERSHIP_COLLECTION, includeDeleted: true }, (record) => record.deleted ||
|
|
491
349
|
(typeof record.body?.space === 'string' && record.key === membershipKey(record.body.space)));
|
|
492
350
|
}
|
|
493
351
|
/**
|
|
@@ -504,7 +362,7 @@ export async function createNode(config) {
|
|
|
504
362
|
return;
|
|
505
363
|
// A view-only invite: what lets the account write is its role in the
|
|
506
364
|
// space, which every device reads there. Invite secrets are never kept.
|
|
507
|
-
const invite = await inviteTo(spaceId);
|
|
365
|
+
const invite = await carrying.inviteTo(spaceId);
|
|
508
366
|
if (known && inviteKeyOf(known.body?.invite) === inviteKeyOf(invite))
|
|
509
367
|
return;
|
|
510
368
|
await open.upsertSystem(MEMBERSHIP_COLLECTION, membershipKey(spaceId), {
|
|
@@ -529,159 +387,6 @@ export async function createNode(config) {
|
|
|
529
387
|
if (await open.get(membershipKey(spaceId)))
|
|
530
388
|
await open.removeSystem(membershipKey(spaceId));
|
|
531
389
|
}
|
|
532
|
-
// ─── Carriers ──────────────────────────────────────────────────────
|
|
533
|
-
//
|
|
534
|
-
// One record per carrier in the registry. Its carry space is derived from
|
|
535
|
-
// the account key and the carrier's key, so every device finds the same one
|
|
536
|
-
// and none is stored. Every device of the account opens it and keeps a pass
|
|
537
|
-
// in it for each of the account's spaces (`space/pass.ts`) — so a space
|
|
538
|
-
// joined in any app is carried, with nothing to do in the home.
|
|
539
|
-
const carrierKey = async (spaceId) => (await passKey(spaceId)).replace(/^pass:/, 'carrier:');
|
|
540
|
-
/** Whether a `sys.carrier` record of the account's, live or not, is keyed by this space */
|
|
541
|
-
async function isCarrySpace(spaceId) {
|
|
542
|
-
if (!accountSpaceId)
|
|
543
|
-
return false;
|
|
544
|
-
const versions = await (await runtime(accountSpaceId)).history(await carrierKey(spaceId));
|
|
545
|
-
return versions.some((version) => version.collection === CARRIER_COLLECTION && version.verified && version.root === config.signer.did);
|
|
546
|
-
}
|
|
547
|
-
const derivedCarry = new Map();
|
|
548
|
-
/** A carrier's carry space: derived, or for one added before they were, the one its invite names */
|
|
549
|
-
async function carrySpaceOf(carrier) {
|
|
550
|
-
if (carrier.invite && carrier.space)
|
|
551
|
-
return (await registry.get(carrier.space)) ?? joinRegistry(carrier.invite).catch(() => null);
|
|
552
|
-
if (!config.accountKey)
|
|
553
|
-
return null;
|
|
554
|
-
const at = `${carrier.did}|${carrier.gen ?? 0}`;
|
|
555
|
-
const known = derivedCarry.get(at);
|
|
556
|
-
if (known)
|
|
557
|
-
return known;
|
|
558
|
-
const derived = deriveCarrySpace(config.accountKey, config.signer.did, carrier.did, carrier.gen ?? 0, provider);
|
|
559
|
-
derivedCarry.set(at, derived);
|
|
560
|
-
return derived;
|
|
561
|
-
}
|
|
562
|
-
/** The account's carriers, live and removed, each with its carry space */
|
|
563
|
-
async function carrierRecords() {
|
|
564
|
-
if (!accountSpaceId)
|
|
565
|
-
return [];
|
|
566
|
-
const found = [];
|
|
567
|
-
for (const record of await ownRecords(await runtime(accountSpaceId), { collection: CARRIER_COLLECTION },
|
|
568
|
-
// A generation is a count: anything else names no carry space.
|
|
569
|
-
(one) => typeof one.body?.did === 'string' &&
|
|
570
|
-
(one.body.gen === undefined || (Number.isSafeInteger(one.body.gen) && one.body.gen >= 0)))) {
|
|
571
|
-
const carry = await carrySpaceOf(record.body);
|
|
572
|
-
// Its key names its carry space: that is how every device knows the space is one.
|
|
573
|
-
if (carry && record.key === (await carrierKey(carry.space.id)))
|
|
574
|
-
found.push({ key: record.key, body: record.body, carry });
|
|
575
|
-
}
|
|
576
|
-
return found;
|
|
577
|
-
}
|
|
578
|
-
/**
|
|
579
|
-
* Puts a pass in a carrier's space for each of the account's spaces, and
|
|
580
|
-
* takes away the rest; and a wake for each of its own automations, each value replaced by
|
|
581
|
-
* the space's tag: the carrier matches, never learns.
|
|
582
|
-
*/
|
|
583
|
-
async function syncPasses(carrier) {
|
|
584
|
-
if (!account || narrowNote)
|
|
585
|
-
return;
|
|
586
|
-
const passes = new Map();
|
|
587
|
-
const spaces = [];
|
|
588
|
-
const owned = await ownAutomations();
|
|
589
|
-
// The registry and the contacts too, so a restore can come through the carrier.
|
|
590
|
-
passes.set(await passKey(account.space.id), await makePass(account));
|
|
591
|
-
if (contactsRecord)
|
|
592
|
-
passes.set(await passKey(contactsRecord.space.id), await makePass(contactsRecord));
|
|
593
|
-
for (const membership of await memberships()) {
|
|
594
|
-
if (membership.deleted || !membership.body || (await kindOf(membership.body.space)))
|
|
595
|
-
continue;
|
|
596
|
-
const record = await registry.get(membership.body.space);
|
|
597
|
-
if (!record)
|
|
598
|
-
continue;
|
|
599
|
-
// Opened even with no wakes to make: opening is also how this device learns the space's key changed.
|
|
600
|
-
const declared = new Map((await (await runtime(record.space.id)).collections()).map((c) => [c.name, c]));
|
|
601
|
-
spaces.push({
|
|
602
|
-
id: record.space.id,
|
|
603
|
-
key: record.key,
|
|
604
|
-
visibility: record.space.visibility,
|
|
605
|
-
topics: (collection) => declared.get(collection)?.topics ?? [],
|
|
606
|
-
computed: (collection) => declared.get(collection)?.computed,
|
|
607
|
-
});
|
|
608
|
-
try {
|
|
609
|
-
passes.set(await passKey(record.space.id), await makePass(record));
|
|
610
|
-
}
|
|
611
|
-
catch {
|
|
612
|
-
// Held without its key — nothing to pass on until it arrives.
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
// Removed meanwhile, on this device or another: its passes stay deleted.
|
|
616
|
-
if (!(await liveCarriers()).some((live) => live.key === carrier.key))
|
|
617
|
-
return;
|
|
618
|
-
const carry = await runtime(carrier.carry.space.id);
|
|
619
|
-
await writeExactly(carry, PASS_COLLECTION, passes, (key) => key.startsWith('pass:'));
|
|
620
|
-
// The links the account keeps, for the carrier to serve while every device is away.
|
|
621
|
-
const links = new Map();
|
|
622
|
-
for (const link of await keptLinks())
|
|
623
|
-
links.set(link.key, link.body);
|
|
624
|
-
await writeExactly(carry, LINK_COLLECTION, links, (key) => key.startsWith('link:'));
|
|
625
|
-
const wakes = new Map();
|
|
626
|
-
for (const own of owned) {
|
|
627
|
-
const wake = await wakeFor(own, spaces, config.signer.did);
|
|
628
|
-
wakes.set(`wake:${own.id}`, wake);
|
|
629
|
-
// A 👍 can make a todo done: what a computed field the automation names reads wakes too.
|
|
630
|
-
for (const also of linkedWakes(own, wake, spaces))
|
|
631
|
-
wakes.set(`wake:${own.id}:${also.collection}`, also);
|
|
632
|
-
}
|
|
633
|
-
await writeExactly(carry, WAKE_COLLECTION, wakes, () => true);
|
|
634
|
-
}
|
|
635
|
-
/** Makes what this account wrote in a collection, among the keys `mine` takes, say exactly `wanted` */
|
|
636
|
-
async function writeExactly(rt, collection, wanted, mine) {
|
|
637
|
-
const held = new Map((await ownRecords(rt, { collection, includeDeleted: true }, (record) => mine(record.key))).map((record) => [record.key, record]));
|
|
638
|
-
for (const [key, body] of wanted) {
|
|
639
|
-
const current = held.get(key);
|
|
640
|
-
if (!current || current.deleted || JSON.stringify(current.body) !== JSON.stringify(body))
|
|
641
|
-
await rt.upsertSystem(collection, key, body);
|
|
642
|
-
held.delete(key);
|
|
643
|
-
}
|
|
644
|
-
for (const [key, record] of held)
|
|
645
|
-
if (!record.deleted)
|
|
646
|
-
await rt.removeSystem(key);
|
|
647
|
-
}
|
|
648
|
-
/** The account's own automations, as it made them */
|
|
649
|
-
async function ownAutomations() {
|
|
650
|
-
if (!accountSpaceId)
|
|
651
|
-
return [];
|
|
652
|
-
const found = await ownRecords(await runtime(accountSpaceId), { collection: OWN_AUTOMATIONS }, (record) => record.key.startsWith('automation:') && checkOwnAutomation(record.body) === null);
|
|
653
|
-
return found
|
|
654
|
-
.map((record) => ({ ...record.body, id: record.key }))
|
|
655
|
-
.sort((a, b) => a.since.localeCompare(b.since));
|
|
656
|
-
}
|
|
657
|
-
/** The carriers the account uses now */
|
|
658
|
-
const liveCarriers = async () => (await carrierRecords()).filter(({ body }) => !body.removed);
|
|
659
|
-
/**
|
|
660
|
-
* Names the account's carriers — its extensions, its hosts — as keepers of
|
|
661
|
-
* a space it manages, and stops naming ones it removed, so apps there hold
|
|
662
|
-
* only what they use. Other keepers the space names stay. Done as each space
|
|
663
|
-
* opens and whenever the carriers change; a space this account doesn't
|
|
664
|
-
* manage is left to whoever does.
|
|
665
|
-
*/
|
|
666
|
-
async function nameKeepers(spaceId, rt) {
|
|
667
|
-
if (!account || narrowNote || (await kindOf(spaceId)))
|
|
668
|
-
return;
|
|
669
|
-
if (!(await rt.may(SPACE_KEEPERS)))
|
|
670
|
-
return;
|
|
671
|
-
const access = await rt.access();
|
|
672
|
-
const carriers = await carrierRecords();
|
|
673
|
-
const active = carriers.filter(({ body }) => !body.removed).map(({ body }) => body);
|
|
674
|
-
const gone = new Set(carriers.filter(({ body }) => body.removed).map(({ body }) => body.did));
|
|
675
|
-
for (const carrier of active)
|
|
676
|
-
gone.delete(carrier.did);
|
|
677
|
-
const kept = access.keepers.filter((keeper) => !gone.has(keeper.did));
|
|
678
|
-
const added = active
|
|
679
|
-
.filter((carrier) => !kept.some((keeper) => keeper.did === carrier.did))
|
|
680
|
-
.map((c) => ({ did: c.did, name: c.name.slice(0, 80) }));
|
|
681
|
-
if (added.length === 0 && kept.length === access.keepers.length)
|
|
682
|
-
return;
|
|
683
|
-
await rt.setKeepers([...kept, ...added].slice(0, MAX_KEEPERS), access.copies);
|
|
684
|
-
}
|
|
685
390
|
/**
|
|
686
391
|
* Makes this node's spaces match the account's: join what the account
|
|
687
392
|
* belongs to, leave what it left, and record anything held here that the
|
|
@@ -723,229 +428,61 @@ export async function createNode(config) {
|
|
|
723
428
|
}
|
|
724
429
|
// Not awaited: it opens every space the account holds, which from a data
|
|
725
430
|
// folder takes long, and nothing here needs it done. Signing in waits on this.
|
|
726
|
-
|
|
431
|
+
inBackground(carrying.passAll());
|
|
727
432
|
// Carriers came or went: the open spaces this account manages say so.
|
|
728
|
-
for (const
|
|
729
|
-
|
|
433
|
+
for (const spaceId of runtimes.keys())
|
|
434
|
+
whenOpen(spaceId, carrying.nameKeepers);
|
|
730
435
|
// Not awaited: a host that is slow to answer must not hold up the rest.
|
|
731
|
-
|
|
436
|
+
inBackground(hosts.keepHosted());
|
|
732
437
|
// Hosts came or went: every open space holds a socket to those the account uses now.
|
|
733
438
|
for (const spaceId of runtimes.keys())
|
|
734
|
-
|
|
439
|
+
inBackground(hosts.reachHosts(spaceId));
|
|
735
440
|
if (changed)
|
|
736
441
|
emit({ type: 'spaces' });
|
|
737
442
|
}
|
|
738
|
-
/** Whether `work` settled within `waitMs` */
|
|
739
|
-
const within = (work, waitMs) => new Promise((resolve) => {
|
|
740
|
-
const timer = setTimeout(() => resolve(false), waitMs);
|
|
741
|
-
void work.then(() => {
|
|
742
|
-
clearTimeout(timer);
|
|
743
|
-
resolve(true);
|
|
744
|
-
}, () => {
|
|
745
|
-
clearTimeout(timer);
|
|
746
|
-
resolve(false);
|
|
747
|
-
});
|
|
748
|
-
});
|
|
749
|
-
/** Writing in carry spaces, one thing at a time: a removal never lands in the middle of a refill */
|
|
750
|
-
let carryTurn = Promise.resolve();
|
|
751
|
-
const inCarryTurn = (work) => {
|
|
752
|
-
const run = carryTurn.catch(() => { }).then(work);
|
|
753
|
-
carryTurn = run;
|
|
754
|
-
return run;
|
|
755
|
-
};
|
|
756
|
-
const mailbox = config.mailbox ?? createMailboxClient();
|
|
757
|
-
// ── Short invite links (spec 03 §7.7) ──
|
|
758
|
-
//
|
|
759
|
-
// The link holds a secret and the hash of one sealed invite; the invite
|
|
760
|
-
// sits in mailboxes: the account's host's first, which keeps it while every
|
|
761
|
-
// device is away, then the relays where the space's members meet.
|
|
762
|
-
/** Where a link's sealed invite is left: its nodes' relays, then the space's or this node's */
|
|
763
|
-
async function linkPlaces(spaceId, nodes) {
|
|
764
|
-
const named = (await findRecord(spaceId))?.relays ?? [];
|
|
765
|
-
const relays = named.length ? named : usableRelays(config.network).slice(0, MAX_RELAYS);
|
|
766
|
-
return [...new Set([...nodes.map(relayOfNode), ...relays])];
|
|
767
|
-
}
|
|
768
|
-
/**
|
|
769
|
-
* A short link to a space: the invite `inviteTo` would give, sealed under a
|
|
770
|
-
* fresh secret and left in mailboxes. Where none takes it, or it is too large
|
|
771
|
-
* for one, the long invite is given instead: it works the same.
|
|
772
|
-
*/
|
|
773
|
-
async function shortInvite(spaceId, secret, options, until) {
|
|
774
|
-
const long = await inviteTo(spaceId, options);
|
|
775
|
-
// The invitation as signed: its secret is the link's to give.
|
|
776
|
-
const invite = parseSpaceInvite(long);
|
|
777
|
-
let sealed;
|
|
778
|
-
try {
|
|
779
|
-
sealed = await sealInvite(secret, { invite: invite.signed, ...(until !== undefined ? { until } : {}) });
|
|
780
|
-
}
|
|
781
|
-
catch {
|
|
782
|
-
return long;
|
|
783
|
-
}
|
|
784
|
-
const topic = await linkTopic(sealed.pin);
|
|
785
|
-
const ttl = until !== undefined ? Math.max(60, Math.ceil((until - Date.now()) / 1000)) : undefined;
|
|
786
|
-
const hosts = new Set((invite.nodes ?? []).map(relayOfNode));
|
|
787
|
-
const places = await linkPlaces(spaceId, invite.nodes ?? []);
|
|
788
|
-
const kept = (await Promise.all(places.map((place) => mailbox.drop(place, topic, sealed.blob, ttl).then(() => place, () => null)))).filter((place) => place !== null);
|
|
789
|
-
if (kept.length === 0)
|
|
790
|
-
return long;
|
|
791
|
-
await keepLink(spaceId, sealed, options, until);
|
|
792
|
-
// A host first, which keeps it; then a relay, so one going away leaves the other.
|
|
793
|
-
const host = kept.find((place) => hosts.has(place));
|
|
794
|
-
const relay = kept.find((place) => !hosts.has(place));
|
|
795
|
-
const named = [host, relay].filter((place) => place !== undefined);
|
|
796
|
-
return encodeInviteLink({ secret, pin: sealed.pin, places: named.slice(0, MAX_LINK_PLACES) });
|
|
797
|
-
}
|
|
798
|
-
/** The links the account keeps, as its registry holds them */
|
|
799
|
-
async function keptLinks() {
|
|
800
|
-
if (!accountSpaceId || narrowNote)
|
|
801
|
-
return [];
|
|
802
|
-
const records = await ownRecords(await runtime(accountSpaceId), { collection: LINK_COLLECTION }, (record) => record.key.startsWith('link:') && isKeptLink(record.body));
|
|
803
|
-
return records.map((record) => ({ key: record.key, body: record.body }));
|
|
804
|
-
}
|
|
805
|
-
/**
|
|
806
|
-
* Keeps a short link's sealed invite in the account registry: what it is
|
|
807
|
-
* for, never its secret. Every device then drops it again while it lasts,
|
|
808
|
-
* and closes its invite when it ends; carriers serve it meanwhile.
|
|
809
|
-
*/
|
|
810
|
-
async function keepLink(spaceId, sealed, options, until) {
|
|
811
|
-
if (!accountSpaceId || narrowNote)
|
|
812
|
-
return;
|
|
813
|
-
const record = await findRecord(spaceId);
|
|
814
|
-
const body = {
|
|
815
|
-
space: spaceId,
|
|
816
|
-
blob: sealed.blob,
|
|
817
|
-
...(options.secret ? { invite: (await deriveInviteKey(options.secret, provider)).did } : {}),
|
|
818
|
-
...(record?.key ? { keyId: record.key.id } : {}),
|
|
819
|
-
...(until !== undefined ? { until } : {}),
|
|
820
|
-
};
|
|
821
|
-
await (await runtime(accountSpaceId)).upsertSystem(LINK_COLLECTION, `link:${bytesToHex(sealed.pin)}`, body);
|
|
822
|
-
void passAll().catch(() => { });
|
|
823
|
-
}
|
|
824
|
-
/** Stops keeping the links `which` picks */
|
|
825
|
-
async function forgetLinks(which) {
|
|
826
|
-
if (!accountSpaceId || narrowNote)
|
|
827
|
-
return;
|
|
828
|
-
const registryRt = await runtime(accountSpaceId);
|
|
829
|
-
let forgot = false;
|
|
830
|
-
for (const { key, body } of await keptLinks())
|
|
831
|
-
if (which(body)) {
|
|
832
|
-
await registryRt.removeSystem(key);
|
|
833
|
-
forgot = true;
|
|
834
|
-
}
|
|
835
|
-
if (forgot)
|
|
836
|
-
void passAll().catch(() => { });
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* Looks after every link the account keeps. One past its `until`, for a
|
|
840
|
-
* space this device no longer holds, or carrying a key the space has moved
|
|
841
|
-
* on from, has ended: its role invite is closed, so nobody holding the
|
|
842
|
-
* space's current key can still join with it, and it is forgotten. The
|
|
843
|
-
* rest are dropped again where the space's members meet; a relay already
|
|
844
|
-
* holding one stores nothing new.
|
|
845
|
-
*/
|
|
846
|
-
const keepLinks = serial(async () => {
|
|
847
|
-
for (const { key, body } of await keptLinks()) {
|
|
848
|
-
if (closed)
|
|
849
|
-
return;
|
|
850
|
-
const record = await registry.get(body.space);
|
|
851
|
-
// Ended only on what this device knows: one behind on a key change, or not holding the space yet,
|
|
852
|
-
// would otherwise end a link another device of the account just made.
|
|
853
|
-
if (!record)
|
|
854
|
-
continue;
|
|
855
|
-
const moved = body.keyId !== undefined &&
|
|
856
|
-
record.key !== null &&
|
|
857
|
-
record.key.id !== body.keyId &&
|
|
858
|
-
(record.keys ?? []).some((held) => held.id === body.keyId);
|
|
859
|
-
if (moved || (body.until !== undefined && body.until <= Date.now())) {
|
|
860
|
-
if (body.invite)
|
|
861
|
-
await closeIfOpen(body.space, body.invite).catch(() => { });
|
|
862
|
-
await forgetLinks((link) => link.blob === body.blob);
|
|
863
|
-
continue;
|
|
864
|
-
}
|
|
865
|
-
const topic = await linkTopic(hexToBytes(key.slice('link:'.length)));
|
|
866
|
-
const ttl = body.until !== undefined ? Math.ceil((body.until - Date.now()) / 1000) : undefined;
|
|
867
|
-
for (const place of await linkPlaces(body.space, []))
|
|
868
|
-
void mailbox.drop(place, topic, body.blob, ttl).catch(() => { });
|
|
869
|
-
}
|
|
870
|
-
});
|
|
871
|
-
/** Closes an invite unless it is closed already, or this account may not */
|
|
872
|
-
async function closeIfOpen(spaceId, inviteDid) {
|
|
873
|
-
const rt = await runtime(spaceId);
|
|
874
|
-
const invite = (await rt.access()).invites.find((held) => held.key === inviteDid);
|
|
875
|
-
if (invite?.open)
|
|
876
|
-
await rt.closeInvite(inviteDid);
|
|
877
|
-
}
|
|
878
|
-
// Relays forget after two weeks or a restart: every hour, whatever is gone goes back.
|
|
879
|
-
const linkTimer = setInterval(() => void keepLinks().catch(() => { }), 60 * 60 * 1000);
|
|
880
|
-
unref(linkTimer);
|
|
881
|
-
/** A short link's invite, fetched once and kept: a preview and the join that follows ask once */
|
|
882
|
-
const resolved = new Map();
|
|
883
|
-
/** The long invite a text holds or a short link names, and when its inviter stops sharing it */
|
|
884
|
-
function resolveInvite(text) {
|
|
885
|
-
const bare = bareInvite(text);
|
|
886
|
-
if (!isShortInvite(bare))
|
|
887
|
-
return Promise.resolve({ long: bare });
|
|
888
|
-
let found = resolved.get(bare);
|
|
889
|
-
if (!found) {
|
|
890
|
-
found = fetchInvite(bare);
|
|
891
|
-
// A preview and the join after it ask once; a few links are remembered, not every one ever read.
|
|
892
|
-
const oldest = resolved.keys().next();
|
|
893
|
-
if (resolved.size >= 16 && !oldest.done)
|
|
894
|
-
resolved.delete(oldest.value);
|
|
895
|
-
resolved.set(bare, found);
|
|
896
|
-
found.catch(() => resolved.delete(bare));
|
|
897
|
-
}
|
|
898
|
-
return found;
|
|
899
|
-
}
|
|
900
|
-
/**
|
|
901
|
-
* Asks every place the link names, and this node's relays, for its topic.
|
|
902
|
-
* Of what comes back, only the blob that hashes to the pin is taken — any
|
|
903
|
-
* other, whoever left it, is ignored unopened.
|
|
904
|
-
*/
|
|
905
|
-
async function fetchInvite(bare) {
|
|
906
|
-
const link = parseInviteLink(bare);
|
|
907
|
-
const { topic, inviteSecret } = await inviteLinkKeys(link.secret, link.pin);
|
|
908
|
-
const places = [...new Set([...link.places, ...usableRelays(config.network)])];
|
|
909
|
-
if (places.length === 0)
|
|
910
|
-
throw new Error('That invite names no place to find it, and this app knows none');
|
|
911
|
-
const blobs = new Set();
|
|
912
|
-
// A slow place can't hold the join up for long: what has come back by then is all there is.
|
|
913
|
-
await Promise.race([
|
|
914
|
-
new Promise((resolve) => unref(setTimeout(resolve, 20_000))),
|
|
915
|
-
Promise.all(places.map((place) => mailbox.fetch(place, topic).then((items) => items.forEach((item) => blobs.add(item.blob)), () => { }))),
|
|
916
|
-
]);
|
|
917
|
-
// Only blobs whose hash is the pin; any other, whoever left it, is never opened.
|
|
918
|
-
const named = [];
|
|
919
|
-
for (const blob of blobs)
|
|
920
|
-
if ((await pinOf(blob)).every((byte, i) => byte === link.pin[i]))
|
|
921
|
-
named.push(blob);
|
|
922
|
-
// Only the inviter could make two blobs share a pin, and then neither is trusted.
|
|
923
|
-
if (named.length > 1)
|
|
924
|
-
throw new Error('That invite link names more than one invite, so it is not used');
|
|
925
|
-
const opened = named[0] ? await openInvite(link, named[0]) : null;
|
|
926
|
-
if (!opened)
|
|
927
|
-
throw new Error('That invite was not found. It may have expired, or the places it names may be down.');
|
|
928
|
-
const { invite, until } = opened;
|
|
929
|
-
// The invitation as its inviter signed it, and beside it the secret the link's own gives a role link.
|
|
930
|
-
const signed = readInvitation(writeInvitation(invite)).version;
|
|
931
|
-
const long = writeInvitation(signed, typeof signed.body.role === 'string' ? inviteSecret : undefined);
|
|
932
|
-
return { long, ...(until !== undefined ? { until } : {}) };
|
|
933
|
-
}
|
|
934
|
-
/** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
|
|
935
|
-
const passAll = serial(() => inCarryTurn(async () => {
|
|
936
|
-
// First: a key change that ends a link is seen here, before its record would be copied on.
|
|
937
|
-
await keepLinks().catch(() => { });
|
|
938
|
-
for (const carrier of await liveCarriers()) {
|
|
939
|
-
if (closed)
|
|
940
|
-
return;
|
|
941
|
-
// Only a device that may write in the carry space can do this; others leave it to one that can.
|
|
942
|
-
await syncPasses(carrier).catch(() => { });
|
|
943
|
-
}
|
|
944
|
-
}));
|
|
945
443
|
const reconcile = serial(() => reconcileOnce().catch((error) => {
|
|
946
444
|
if (!closed)
|
|
947
445
|
console.error('Could not reconcile the account registry:', error);
|
|
948
446
|
}));
|
|
447
|
+
// ─── The parts ─────────────────────────────────────────────────────
|
|
448
|
+
const ctx = Object.freeze({
|
|
449
|
+
config,
|
|
450
|
+
provider,
|
|
451
|
+
registry,
|
|
452
|
+
account,
|
|
453
|
+
accountSpaceId,
|
|
454
|
+
contactsRecord,
|
|
455
|
+
contactsSpaceId,
|
|
456
|
+
contactKeys,
|
|
457
|
+
narrowNote,
|
|
458
|
+
mailbox: config.mailbox ?? createMailboxClient(),
|
|
459
|
+
emit,
|
|
460
|
+
subscribe: events.subscribe,
|
|
461
|
+
isClosed: () => closed,
|
|
462
|
+
looseSigner,
|
|
463
|
+
runtime,
|
|
464
|
+
runtimes,
|
|
465
|
+
findRecord,
|
|
466
|
+
kindOf,
|
|
467
|
+
joinRegistry,
|
|
468
|
+
requireAccount,
|
|
469
|
+
ownRecords,
|
|
470
|
+
accountRecords,
|
|
471
|
+
memberships,
|
|
472
|
+
// Parts made below: read them only after createNode returns, never while a part is being built.
|
|
473
|
+
get spaces() {
|
|
474
|
+
return spaces;
|
|
475
|
+
},
|
|
476
|
+
get carrying() {
|
|
477
|
+
return carrying;
|
|
478
|
+
},
|
|
479
|
+
get hosts() {
|
|
480
|
+
return hosts;
|
|
481
|
+
},
|
|
482
|
+
});
|
|
483
|
+
const carrying = createNodeCarriers(ctx);
|
|
484
|
+
const hosts = createNodeHosting(ctx);
|
|
485
|
+
const people = createNodeContacts(ctx);
|
|
949
486
|
const spaces = Object.freeze({
|
|
950
487
|
async list() {
|
|
951
488
|
const used = [];
|
|
@@ -977,7 +514,9 @@ export async function createNode(config) {
|
|
|
977
514
|
async invite(spaceId, options = {}) {
|
|
978
515
|
// A short link's secret comes first: a role invite's own secret is derived from it.
|
|
979
516
|
const link = options.short ? generateLinkSecret() : null;
|
|
980
|
-
const share = (opened = {}) => link
|
|
517
|
+
const share = (opened = {}) => link
|
|
518
|
+
? carrying.shortInvite(spaceId, link, opened, options.until)
|
|
519
|
+
: carrying.inviteTo(spaceId, opened);
|
|
981
520
|
if (options.write === false)
|
|
982
521
|
return share();
|
|
983
522
|
const open = await runtime(spaceId);
|
|
@@ -1000,7 +539,7 @@ export async function createNode(config) {
|
|
|
1000
539
|
return share({ secret, role });
|
|
1001
540
|
},
|
|
1002
541
|
async preview(invite) {
|
|
1003
|
-
const { long, until } = await resolveInvite(invite);
|
|
542
|
+
const { long, until } = await carrying.resolveInvite(invite);
|
|
1004
543
|
// Who it says invited is shown before joining, so it is checked as joining checks it.
|
|
1005
544
|
const parsed = parseSpaceInvite(long);
|
|
1006
545
|
const unsigned = await checkInvitation(parsed.signed, provider, parsed.invite);
|
|
@@ -1009,7 +548,7 @@ export async function createNode(config) {
|
|
|
1009
548
|
return { ...previewInvite(long), ...(until !== undefined ? { until } : {}) };
|
|
1010
549
|
},
|
|
1011
550
|
async join(invite, options = {}) {
|
|
1012
|
-
const record = await joinRegistry((await resolveInvite(invite)).long);
|
|
551
|
+
const record = await joinRegistry((await carrying.resolveInvite(invite)).long);
|
|
1013
552
|
if (options.memberKey)
|
|
1014
553
|
await registry.setMemberKey(record.space.id, options.memberKey);
|
|
1015
554
|
// A runtime opened before the key arrived would still be unable to read.
|
|
@@ -1061,7 +600,7 @@ export async function createNode(config) {
|
|
|
1061
600
|
// A peer's key does not say whose it is. But only this account's devices
|
|
1062
601
|
// and apps can read the account registry, so a peer there is one of ours
|
|
1063
602
|
// — except a carrier, which the registry names by its key.
|
|
1064
|
-
const carrierKeys = new Set((await liveCarriers()).map(({ body }) => body.did));
|
|
603
|
+
const carrierKeys = new Set((await carrying.liveCarriers()).map(({ body }) => body.did));
|
|
1065
604
|
const inRegistry = new Set((await (await runtime(accountSpaceId)).status()).peers);
|
|
1066
605
|
return {
|
|
1067
606
|
...status,
|
|
@@ -1073,15 +612,15 @@ export async function createNode(config) {
|
|
|
1073
612
|
if (!accountSpaceId || narrowNote || !config.network)
|
|
1074
613
|
return false;
|
|
1075
614
|
// Only with a carrier connected now, as the account registry shows it: else nothing is coming.
|
|
1076
|
-
const carriers = new Set((await liveCarriers()).map(({ body }) => body.did));
|
|
615
|
+
const carriers = new Set((await carrying.liveCarriers()).map(({ body }) => body.did));
|
|
1077
616
|
const online = (await (await runtime(accountSpaceId)).status()).peers;
|
|
1078
617
|
if (!online.some((peer) => carriers.has(peer)))
|
|
1079
618
|
return false;
|
|
1080
619
|
const deadline = Date.now() + (options.waitMs ?? CARRIED_WAIT_MS);
|
|
1081
620
|
const open = await runtime(spaceId);
|
|
1082
621
|
// Named a keeper, and given its pass now rather than whenever the next round comes.
|
|
1083
|
-
await nameKeepers(spaceId, open).catch(() => { });
|
|
1084
|
-
|
|
622
|
+
await carrying.nameKeepers(spaceId, open).catch(() => { });
|
|
623
|
+
inBackground(carrying.passAll());
|
|
1085
624
|
while (!closed && Date.now() < deadline) {
|
|
1086
625
|
// Level with a carrier: it holds the genesis, and any invite opened since.
|
|
1087
626
|
for (const peer of (await spaces.status(spaceId)).carriers)
|
|
@@ -1091,6 +630,8 @@ export async function createNode(config) {
|
|
|
1091
630
|
}
|
|
1092
631
|
return false;
|
|
1093
632
|
},
|
|
633
|
+
// At most a minute: a wait, not a way to keep a timer for days.
|
|
634
|
+
reached: perSpace((rt, peer, waitMs) => rt.syncedWith(peer, Math.min(waitMs, 60_000))),
|
|
1094
635
|
profiles: perSpace((rt) => rt.profiles()),
|
|
1095
636
|
access: perSpace((rt) => rt.access()),
|
|
1096
637
|
may: perSpace((rt, cmd, args, account) => rt.may(cmd, args, account)),
|
|
@@ -1108,22 +649,10 @@ export async function createNode(config) {
|
|
|
1108
649
|
await (await runtime(spaceId)).succeed(successor);
|
|
1109
650
|
},
|
|
1110
651
|
async closeInvite(spaceId, keyOrLink) {
|
|
1111
|
-
|
|
1112
|
-
// The link itself will do: its secret names the invite.
|
|
1113
|
-
if (!keyOrLink.startsWith('did:key:') && isShortInvite(bareInvite(keyOrLink))) {
|
|
1114
|
-
// A short link's invite secret is derived from its own; a view-only one has no record to close.
|
|
1115
|
-
const secret = await linkInviteSecret(parseInviteLink(bareInvite(keyOrLink)).secret);
|
|
1116
|
-
key = (await deriveInviteKey(secret, provider)).did;
|
|
1117
|
-
}
|
|
1118
|
-
else if (!keyOrLink.startsWith('did:key:')) {
|
|
1119
|
-
const secret = parseSpaceInvite(bareInvite(keyOrLink)).invite;
|
|
1120
|
-
if (!secret)
|
|
1121
|
-
throw new Error('That invite is view-only — there is nothing to close. To stop it working, give the space a new key (changeKey).');
|
|
1122
|
-
key = (await deriveInviteKey(base64UrlDecode(secret), provider)).did;
|
|
1123
|
-
}
|
|
652
|
+
const key = await carrying.inviteKeyOf(keyOrLink);
|
|
1124
653
|
await (await runtime(spaceId)).closeInvite(key);
|
|
1125
654
|
// Its link, if the account keeps one, is no longer served.
|
|
1126
|
-
await forgetLinks((link) => link.space === spaceId && link.invite === key);
|
|
655
|
+
await carrying.forgetLinks((link) => link.space === spaceId && link.invite === key);
|
|
1127
656
|
},
|
|
1128
657
|
revoke: perSpace((rt, key, options) => rt.revoke(key, options)),
|
|
1129
658
|
changeKey: perSpace((rt) => rt.rotateKey()),
|
|
@@ -1140,1338 +669,26 @@ export async function createNode(config) {
|
|
|
1140
669
|
return createServerAuth(spaceId, read, sessionKeys.privateKey, provider, () => current);
|
|
1141
670
|
},
|
|
1142
671
|
});
|
|
1143
|
-
|
|
1144
|
-
// node learns which spaces it belongs to.
|
|
1145
|
-
if (accountSpaceId) {
|
|
1146
|
-
await runtime(accountSpaceId);
|
|
1147
|
-
await reconcile();
|
|
1148
|
-
}
|
|
1149
|
-
/** Writes one of the account's own automations, checked, and hands every carrier the wakes as they are now */
|
|
1150
|
-
async function writeOwn(id, body) {
|
|
1151
|
-
const registryRt = await requireAccount('Making an automation');
|
|
1152
|
-
const problem = checkOwnAutomation(body);
|
|
1153
|
-
if (problem)
|
|
1154
|
-
throw new Error(problem);
|
|
1155
|
-
// A system collection: nothing defines it, so no other key of the account can make it final.
|
|
1156
|
-
await registryRt.upsertSystem(OWN_AUTOMATIONS, id, body);
|
|
1157
|
-
// Every carrier gets the wakes as they are now, in the background (`carriers.settled`).
|
|
1158
|
-
void passAll().catch(() => { });
|
|
1159
|
-
return { ...body, id };
|
|
1160
|
-
}
|
|
1161
|
-
const automations = Object.freeze({
|
|
1162
|
-
list: ownAutomations,
|
|
1163
|
-
add: (own) => writeOwn(`automation:${base32Encode(globalThis.crypto.getRandomValues(new Uint8Array(10)))}`, {
|
|
1164
|
-
...own,
|
|
1165
|
-
name: own.name.trim(),
|
|
1166
|
-
since: own.since ?? new Date().toISOString(),
|
|
1167
|
-
}),
|
|
1168
|
-
async update(id, changes) {
|
|
1169
|
-
await requireAccount('Making an automation');
|
|
1170
|
-
const current = (await ownAutomations()).find((view) => view.id === id);
|
|
1171
|
-
if (!current)
|
|
1172
|
-
throw new Error('There is no such automation');
|
|
1173
|
-
const { id: _id, ...was } = current;
|
|
1174
|
-
return writeOwn(id, {
|
|
1175
|
-
...was,
|
|
1176
|
-
...(changes.name !== undefined ? { name: changes.name.trim() } : {}),
|
|
1177
|
-
...(changes.paused !== undefined ? { paused: changes.paused } : {}),
|
|
1178
|
-
});
|
|
1179
|
-
},
|
|
1180
|
-
async remove(id) {
|
|
1181
|
-
const registryRt = await requireAccount('Making an automation');
|
|
1182
|
-
if (!(await ownAutomations()).some((view) => view.id === id))
|
|
1183
|
-
return;
|
|
1184
|
-
await registryRt.removeSystem(id);
|
|
1185
|
-
void passAll().catch(() => { });
|
|
1186
|
-
},
|
|
1187
|
-
async versions(ids) {
|
|
1188
|
-
if (!accountSpaceId)
|
|
1189
|
-
return [];
|
|
1190
|
-
const keys = ids.filter((id) => id.startsWith('automation:'));
|
|
1191
|
-
return (await (await runtime(accountSpaceId)).versionsOf(keys)).filter((version) => version.collection === OWN_AUTOMATIONS);
|
|
1192
|
-
},
|
|
1193
|
-
async take(versions) {
|
|
1194
|
-
if (!accountSpaceId)
|
|
1195
|
-
return 0;
|
|
1196
|
-
// The account's own automations only: whatever else rides along waits for sync.
|
|
1197
|
-
const mine = versions.filter((version) => typeof version === 'object' &&
|
|
1198
|
-
version !== null &&
|
|
1199
|
-
version.collection === OWN_AUTOMATIONS &&
|
|
1200
|
-
version.space === accountSpaceId);
|
|
1201
|
-
if (mine.length === 0)
|
|
1202
|
-
return 0;
|
|
1203
|
-
const taken = await (await runtime(accountSpaceId)).take(mine);
|
|
1204
|
-
if (taken > 0)
|
|
1205
|
-
void passAll().catch(() => { });
|
|
1206
|
-
return taken;
|
|
1207
|
-
},
|
|
1208
|
-
});
|
|
1209
|
-
const carriers = Object.freeze({
|
|
1210
|
-
list: async () => (await liveCarriers()).map(({ body: { did, name, since }, carry }) => ({
|
|
1211
|
-
space: carry.space.id,
|
|
1212
|
-
did,
|
|
1213
|
-
name,
|
|
1214
|
-
since,
|
|
1215
|
-
})),
|
|
1216
|
-
async add(carrier) {
|
|
1217
|
-
const registryRt = await requireAccount('Using a carrier');
|
|
1218
|
-
const all = await carrierRecords();
|
|
1219
|
-
// The same carrier again keeps its carry space: what it holds stays good, and nothing is closed under it.
|
|
1220
|
-
let entry = all.find(({ body }) => body.did === carrier.did && !body.removed);
|
|
1221
|
-
if (entry)
|
|
1222
|
-
void passAll().catch(() => { });
|
|
1223
|
-
else {
|
|
1224
|
-
// Added again after a removal, a new carry space: the last one tells it to forget. One past the
|
|
1225
|
-
// highest seen, not a count: a device that hasn't synced every earlier one must not land on a closed space.
|
|
1226
|
-
const gens = all.filter(({ body }) => body.did === carrier.did).map(({ body }) => body.gen ?? 0);
|
|
1227
|
-
const gen = gens.length ? Math.max(...gens) + 1 : 0;
|
|
1228
|
-
const body = {
|
|
1229
|
-
did: carrier.did,
|
|
1230
|
-
name: carrier.name.trim().slice(0, 80) || 'Carrier',
|
|
1231
|
-
since: new Date().toISOString(),
|
|
1232
|
-
...(gen ? { gen } : {}),
|
|
1233
|
-
};
|
|
1234
|
-
const carry = (await carrySpaceOf(body));
|
|
1235
|
-
// Two devices adding it at once write the one record, for the one space.
|
|
1236
|
-
entry = { key: await carrierKey(carry.space.id), body, carry };
|
|
1237
|
-
await registryRt.upsertSystem(CARRIER_COLLECTION, entry.key, body);
|
|
1238
|
-
// Its passes before its invite, as one batch: a carrier joining an empty carry space takes spaces as they trickle in.
|
|
1239
|
-
// Not in turn behind a refill: nothing removes a carrier that is only now being added.
|
|
1240
|
-
await syncPasses(entry);
|
|
1241
|
-
}
|
|
1242
|
-
return {
|
|
1243
|
-
space: entry.carry.space.id,
|
|
1244
|
-
invite: await encodeSpaceInvite(entry.carry, looseSigner(), provider),
|
|
1245
|
-
};
|
|
1246
|
-
},
|
|
1247
|
-
settled: (waitMs) => within(passAll.done(), waitMs),
|
|
1248
|
-
async reached(spaceId, waitMs) {
|
|
1249
|
-
const did = (await liveCarriers()).find(({ carry }) => carry.space.id === spaceId)?.body.did;
|
|
1250
|
-
if (!did || !accountSpaceId)
|
|
1251
|
-
return false;
|
|
1252
|
-
const deadline = Date.now() + waitMs;
|
|
1253
|
-
// Level with the passes and wakes as they are now: a refill under way first, within the same time.
|
|
1254
|
-
await within(passAll.done(), waitMs);
|
|
1255
|
-
// Its passes first: only through them does it come to the registry, and hold its own record there.
|
|
1256
|
-
if (!(await (await runtime(spaceId)).syncedWith(did, Math.max(0, deadline - Date.now()))))
|
|
1257
|
-
return false;
|
|
1258
|
-
return (await runtime(accountSpaceId)).syncedWith(did, Math.max(0, deadline - Date.now()));
|
|
1259
|
-
},
|
|
1260
|
-
async remove(spaceId) {
|
|
1261
|
-
const registryRt = await requireAccount('Removing a carrier');
|
|
1262
|
-
// In turn with any refill, which would otherwise put the passes back.
|
|
1263
|
-
await inCarryTurn(async () => {
|
|
1264
|
-
const live = await liveCarriers();
|
|
1265
|
-
const did = live.find(({ carry }) => carry.space.id === spaceId)?.body.did;
|
|
1266
|
-
// Every carry space it has: one added on two devices at once, before they were derived, has two.
|
|
1267
|
-
for (const { key, body, carry } of live.filter((one) => one.body.did === did)) {
|
|
1268
|
-
const rt = await runtime(carry.space.id);
|
|
1269
|
-
// Passes gone first, then the word to forget everything, then the carrier's record.
|
|
1270
|
-
for (const pass of await ownRecords(rt, { collection: PASS_COLLECTION }, (r) => r.key.startsWith('pass:')))
|
|
1271
|
-
await rt.removeSystem(pass.key);
|
|
1272
|
-
await rt.upsertSystem(PASS_COLLECTION, CARRY_CLOSED_KEY, { v: 1, closed: true });
|
|
1273
|
-
// Kept, so adding it again counts this one and takes a new carry space.
|
|
1274
|
-
await registryRt.upsertSystem(CARRIER_COLLECTION, key, {
|
|
1275
|
-
...body,
|
|
1276
|
-
removed: new Date().toISOString(),
|
|
1277
|
-
});
|
|
1278
|
-
}
|
|
1279
|
-
});
|
|
1280
|
-
},
|
|
1281
|
-
});
|
|
1282
|
-
// ─── Hosting ───────────────────────────────────────────────────────
|
|
1283
|
-
//
|
|
1284
|
-
// A host is a carrier the account pays for. The subscription key lives in
|
|
1285
|
-
// the registry (`sys.hosting`), so every device signs as the same
|
|
1286
|
-
// subscription, and any of them hands the host the carry space once it is
|
|
1287
|
-
// paid — the one that paid, or the next one to notice.
|
|
1288
|
-
const hostingKey = (url) => hashedKey('hosting', url);
|
|
1289
|
-
/** The hosting records the account wrote, live */
|
|
1290
|
-
async function hostingRecords() {
|
|
1291
|
-
if (!accountSpaceId)
|
|
1292
|
-
return [];
|
|
1293
|
-
const records = await ownRecords(await runtime(accountSpaceId), { collection: HOSTING_COLLECTION }, (record) => typeof record.body?.url === 'string' && typeof record.body.seed === 'string');
|
|
1294
|
-
return records.map((record) => record.body);
|
|
1295
|
-
}
|
|
1296
|
-
async function hostClient(hosting) {
|
|
1297
|
-
const key = await subscriptionKey(base64UrlDecode(hosting.seed), provider);
|
|
1298
|
-
return { client: createHostClient(hosting.url, hosting.host, key, provider), subscription: key.did };
|
|
1299
|
-
}
|
|
1300
|
-
/** What the host at a known address says about itself — refused when it's another host now */
|
|
1301
|
-
async function describeKnown(hosting) {
|
|
1302
|
-
const description = await describeHost(hosting.url);
|
|
1303
|
-
if (description.did !== hosting.host)
|
|
1304
|
-
throw new Error("The host at this address has another key now, so it's another host");
|
|
1305
|
-
return description;
|
|
1306
|
-
}
|
|
1307
|
-
/** Last time each host was handed the spaces, or refused them — so asking again waits a while */
|
|
1308
|
-
const handedAt = new Map();
|
|
1309
|
-
const HAND_AGAIN_MS = 60_000;
|
|
1310
|
-
/** Handovers under way, so a second look waits for the first instead of reporting the spaces not carried */
|
|
1311
|
-
const handing = new Map();
|
|
1312
|
-
/**
|
|
1313
|
-
* Keeps what the host signed in the registry, so every device shows it and
|
|
1314
|
-
* the person holds the host's word — written only when what it says changed.
|
|
1315
|
-
*/
|
|
1316
|
-
async function keepReceipt(hosting, kept, status, receipt, description) {
|
|
1317
|
-
if (narrowNote || !accountSpaceId)
|
|
1318
|
-
return;
|
|
1319
|
-
const { name } = description;
|
|
1320
|
-
const peer = hostPeerAddress(hosting.url, description) ?? undefined;
|
|
1321
|
-
const same = kept &&
|
|
1322
|
-
kept.state === status.state &&
|
|
1323
|
-
kept.paidUntil === status.paidUntil &&
|
|
1324
|
-
kept.renews === status.renews &&
|
|
1325
|
-
kept.plan === status.plan &&
|
|
1326
|
-
JSON.stringify(kept.over ?? []) === JSON.stringify(status.over ?? []) &&
|
|
1327
|
-
hosting.name === name &&
|
|
1328
|
-
hosting.peer === peer;
|
|
1329
|
-
if (same)
|
|
1330
|
-
return;
|
|
1331
|
-
const { peer: _before, ...rest } = hosting;
|
|
1332
|
-
const record = { ...rest, name, receipt, ...(peer ? { peer } : {}) };
|
|
1333
|
-
await (await runtime(accountSpaceId)).upsertSystem(HOSTING_COLLECTION, await hostingKey(hosting.url), record);
|
|
1334
|
-
}
|
|
1335
|
-
/** Asks a host how it stands, and hands it the spaces if it is paid for but not carrying them */
|
|
1336
|
-
async function viewHosting(hosting, force = false) {
|
|
1337
|
-
const { client, subscription } = await hostClient(hosting);
|
|
1338
|
-
const kept = hosting.receipt ? await readStatus(hosting.receipt, hosting.host, provider) : null;
|
|
1339
|
-
const base = { url: hosting.url, host: hosting.host, subscription, since: hosting.since };
|
|
1340
|
-
try {
|
|
1341
|
-
const description = await describeKnown(hosting);
|
|
1342
|
-
let { status, receipt } = await client.status();
|
|
1343
|
-
const due = force || Date.now() - (handedAt.get(hosting.url) ?? 0) > HAND_AGAIN_MS;
|
|
1344
|
-
// A host with limits keeps an account's spaces with nothing paid: its free plan.
|
|
1345
|
-
const paid = status.state === 'active' ||
|
|
1346
|
-
status.state === 'grace' ||
|
|
1347
|
-
((description.free || description.limits !== undefined) && status.state !== 'lapsed');
|
|
1348
|
-
const inFlight = handing.get(hosting.url);
|
|
1349
|
-
if (!status.carrying && inFlight) {
|
|
1350
|
-
// Another look is handing the spaces over right now: wait for it,
|
|
1351
|
-
// rather than answer "not carrying" while they're on their way.
|
|
1352
|
-
const handed = await inFlight.catch(() => null);
|
|
1353
|
-
if (handed)
|
|
1354
|
-
({ status, receipt } = handed);
|
|
1355
|
-
}
|
|
1356
|
-
else if (!status.carrying && paid && due && !narrowNote) {
|
|
1357
|
-
handedAt.set(hosting.url, Date.now());
|
|
1358
|
-
const attaching = carriers
|
|
1359
|
-
.add({ did: hosting.host, name: new URL(hosting.url).host })
|
|
1360
|
-
.then(({ invite }) => client.attach(config.signer.did, invite));
|
|
1361
|
-
handing.set(hosting.url, attaching);
|
|
1362
|
-
try {
|
|
1363
|
-
({ status, receipt } = await attaching);
|
|
1364
|
-
}
|
|
1365
|
-
catch (error) {
|
|
1366
|
-
// Not paid after all (it lapsed in between): the status says so.
|
|
1367
|
-
if (!(error instanceof HostError && error.status === 402))
|
|
1368
|
-
throw error;
|
|
1369
|
-
}
|
|
1370
|
-
finally {
|
|
1371
|
-
handing.delete(hosting.url);
|
|
1372
|
-
}
|
|
1373
|
-
}
|
|
1374
|
-
await keepReceipt(hosting, kept, status, receipt, description);
|
|
1375
|
-
return {
|
|
1376
|
-
...base,
|
|
1377
|
-
name: description.name,
|
|
1378
|
-
status,
|
|
1379
|
-
live: true,
|
|
1380
|
-
fund: description.free ? null : (description.fund ?? null),
|
|
1381
|
-
reminds: description.remind === true,
|
|
1382
|
-
};
|
|
1383
|
-
}
|
|
1384
|
-
catch (error) {
|
|
1385
|
-
return {
|
|
1386
|
-
...base,
|
|
1387
|
-
name: hosting.name ?? new URL(hosting.url).host,
|
|
1388
|
-
status: kept,
|
|
1389
|
-
live: false,
|
|
1390
|
-
fund: null,
|
|
1391
|
-
reminds: false,
|
|
1392
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1393
|
-
};
|
|
1394
|
-
}
|
|
1395
|
-
}
|
|
1396
|
-
/** Every device keeps its hosts carrying: after the registry changes, ask each once more */
|
|
1397
|
-
async function keepHosted() {
|
|
1398
|
-
if (narrowNote)
|
|
1399
|
-
return;
|
|
1400
|
-
for (const hosting of await hostingRecords())
|
|
1401
|
-
await viewHosting(hosting).catch(() => { });
|
|
1402
|
-
}
|
|
1403
|
-
async function requireHosting(url) {
|
|
1404
|
-
const found = (await hostingRecords()).find((hosting) => hosting.url === url);
|
|
1405
|
-
if (!found)
|
|
1406
|
-
throw new Error(`This account doesn't use the host at ${url}`);
|
|
1407
|
-
return found;
|
|
1408
|
-
}
|
|
1409
|
-
/** An address a device may reach: https://, or http:// on this machine */
|
|
1410
|
-
function checkAddress(address, what) {
|
|
1411
|
-
const url = new URL(address);
|
|
1412
|
-
const local = ['localhost', '127.0.0.1'].includes(url.hostname);
|
|
1413
|
-
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local))
|
|
1414
|
-
throw new Error(`${what} is reached over https://`);
|
|
1415
|
-
return url;
|
|
1416
|
-
}
|
|
1417
|
-
// ─── A space paying for itself ─────────────────────────────────────
|
|
1418
|
-
//
|
|
1419
|
-
// A space names the hosts it pays in `std.host` records, which only those
|
|
1420
|
-
// who may manage it write. Any member's device holding the space key hands
|
|
1421
|
-
// such a host the space's pass once someone has paid there, and again when
|
|
1422
|
-
// the space's key changes, so the host carries it without reading it.
|
|
1423
|
-
/** When each space last asked its hosts, and what it named then: asked again after a while, or when that changed */
|
|
1424
|
-
const spaceHostsAsked = new Map();
|
|
1425
|
-
const SPACE_HOSTS_EVERY_MS = 10 * 60_000;
|
|
1426
|
-
async function namedHosts(spaceId) {
|
|
1427
|
-
const rt = await runtime(spaceId);
|
|
1428
|
-
// Only where the space keeps hosts: listing a collection makes a space held in part hold it.
|
|
1429
|
-
if (!(await rt.collections()).some((c) => c.name === 'std.host' && c.version !== null))
|
|
1430
|
-
return [];
|
|
1431
|
-
const records = await rt.list({ collection: 'std.host' });
|
|
1432
|
-
return records.flatMap((record) => {
|
|
1433
|
-
const body = record.body;
|
|
1434
|
-
if (!record.verified || record.deleted || !isRecord(body) || typeof body.url !== 'string')
|
|
1435
|
-
return [];
|
|
1436
|
-
let url;
|
|
1437
|
-
try {
|
|
1438
|
-
url = checkAddress(body.url, 'A host').origin;
|
|
1439
|
-
}
|
|
1440
|
-
catch {
|
|
1441
|
-
return [];
|
|
1442
|
-
}
|
|
1443
|
-
return [
|
|
1444
|
-
{
|
|
1445
|
-
url,
|
|
1446
|
-
...(typeof body.did === 'string' ? { did: body.did } : {}),
|
|
1447
|
-
...(typeof body.name === 'string' ? { name: body.name } : {}),
|
|
1448
|
-
},
|
|
1449
|
-
];
|
|
1450
|
-
});
|
|
1451
|
-
}
|
|
1452
|
-
/** The read key a space is carried with now, as a DID: what a host should hold */
|
|
1453
|
-
const currentReadKey = (pass) => pass.readKey ?? pass.space.readKey;
|
|
1454
|
-
async function askSpaceHost(spaceId, named, hand) {
|
|
1455
|
-
try {
|
|
1456
|
-
const description = await describeHost(named.url);
|
|
1457
|
-
// A host whose key changed since the space chose it is not the host it chose.
|
|
1458
|
-
if (named.did && named.did !== description.did)
|
|
1459
|
-
throw new Error('The host’s key changed');
|
|
1460
|
-
const client = createSpaceHostClient(named.url, description.did, provider);
|
|
1461
|
-
let { status } = await client.status(spaceId);
|
|
1462
|
-
// Paid, or a free host that hasn't let it lapse, as for an account's subscription.
|
|
1463
|
-
const paid = status.state === 'active' ||
|
|
1464
|
-
status.state === 'grace' ||
|
|
1465
|
-
(description.free && status.state !== 'lapsed');
|
|
1466
|
-
const record = hand && paid ? await findRecord(spaceId) : null;
|
|
1467
|
-
if (record && (record.space.visibility === 'public' || record.key)) {
|
|
1468
|
-
const pass = await makePass(record);
|
|
1469
|
-
if (!status.carrying || (pass.read && status.readKey !== currentReadKey(pass)))
|
|
1470
|
-
({ status } = await client.hand(spaceId, pass));
|
|
1471
|
-
}
|
|
1472
|
-
return {
|
|
1473
|
-
url: named.url,
|
|
1474
|
-
name: named.name ?? description.name,
|
|
1475
|
-
host: description.did,
|
|
1476
|
-
status,
|
|
1477
|
-
free: description.free === true,
|
|
1478
|
-
fund: description.free ? null : (description.fund ?? null),
|
|
1479
|
-
reminds: description.remind === true,
|
|
1480
|
-
runsBots: description.bots === true,
|
|
1481
|
-
bots: status.bots ?? [],
|
|
1482
|
-
connectors: description.bots === true ? connectorOffers(description.connectors) : [],
|
|
1483
|
-
};
|
|
1484
|
-
}
|
|
1485
|
-
catch (error) {
|
|
1486
|
-
return {
|
|
1487
|
-
url: named.url,
|
|
1488
|
-
name: named.name ?? new URL(named.url).hostname,
|
|
1489
|
-
host: null,
|
|
1490
|
-
status: null,
|
|
1491
|
-
free: false,
|
|
1492
|
-
fund: null,
|
|
1493
|
-
reminds: false,
|
|
1494
|
-
runsBots: false,
|
|
1495
|
-
bots: [],
|
|
1496
|
-
connectors: [],
|
|
1497
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1498
|
-
};
|
|
1499
|
-
}
|
|
1500
|
-
}
|
|
1501
|
-
/** A client for a host a space names, checked to be the host it chose */
|
|
1502
|
-
async function spaceHostClient(spaceId, url) {
|
|
1503
|
-
const named = (await namedHosts(spaceId)).find((known) => known.url === url);
|
|
1504
|
-
if (!named)
|
|
1505
|
-
throw new Error('This space doesn’t use the host at that address');
|
|
1506
|
-
const description = await describeHost(named.url);
|
|
1507
|
-
if (named.did && named.did !== description.did)
|
|
1508
|
-
throw new Error('The host’s key changed');
|
|
1509
|
-
return createSpaceHostClient(named.url, description.did, provider);
|
|
1510
|
-
}
|
|
1511
|
-
/** Hands the hosts a space names its pass, when they were paid and don't carry it with its key yet */
|
|
1512
|
-
async function keepSpaceHosts(spaceId) {
|
|
1513
|
-
// Only while it is open: a change heard as it closed must not open it again.
|
|
1514
|
-
if ((await kindOf(spaceId)) || !runtimes.has(spaceId))
|
|
1515
|
-
return;
|
|
1516
|
-
const hosts = await namedHosts(spaceId);
|
|
1517
|
-
await reachHosts(spaceId, hosts);
|
|
1518
|
-
if (narrowNote)
|
|
1519
|
-
return;
|
|
1520
|
-
const named = hosts.map((h) => h.url).join(' ');
|
|
1521
|
-
const asked = spaceHostsAsked.get(spaceId);
|
|
1522
|
-
if (!hosts.length || (asked?.named === named && Date.now() - asked.at < SPACE_HOSTS_EVERY_MS))
|
|
1523
|
-
return;
|
|
1524
|
-
spaceHostsAsked.set(spaceId, { at: Date.now(), named });
|
|
1525
|
-
for (const known of hosts)
|
|
1526
|
-
await askSpaceHost(spaceId, known, true);
|
|
1527
|
-
}
|
|
1528
|
-
// ─── Reaching hosts ────────────────────────────────────────────────
|
|
1529
|
-
//
|
|
1530
|
-
// A host is reached over its socket, at the address its description names
|
|
1531
|
-
// (`peer`). Every space holds one to each host the account uses, as the
|
|
1532
|
-
// account's carry space names them all; a space also holds one to each host
|
|
1533
|
-
// it pays itself (`std.host`). The account registry also tries the hosts
|
|
1534
|
-
// the node was built with (`network.hosts`), so a new device with only the
|
|
1535
|
-
// recovery code finds its registry there, and every space from it.
|
|
1536
|
-
/** Each host's socket address, as its description said: asked once, and again after a failure */
|
|
1537
|
-
/** A node address pinned to a key (spec 04 §5.2); one without a key to pin stays as it is */
|
|
1538
|
-
const pinnedTo = (address, did) => address && did?.startsWith('did:key:') ? `${address.split('#')[0]}#${did}` : address;
|
|
1539
|
-
const describedPeers = new Map();
|
|
1540
|
-
function describedPeer(url) {
|
|
1541
|
-
let found = describedPeers.get(url);
|
|
1542
|
-
if (!found) {
|
|
1543
|
-
found = describeHost(url).then((description) => pinnedTo(hostPeerAddress(url, description), description.did), () => {
|
|
1544
|
-
describedPeers.delete(url);
|
|
1545
|
-
return null;
|
|
1546
|
-
});
|
|
1547
|
-
describedPeers.set(url, found);
|
|
1548
|
-
}
|
|
1549
|
-
return found;
|
|
1550
|
-
}
|
|
1551
|
-
/**
|
|
1552
|
-
* A host's socket address: the one written down with it, or its
|
|
1553
|
-
* description's. Pinned to the key written down with it when there is one,
|
|
1554
|
-
* else the key it described itself with, so another node answering there is refused.
|
|
1555
|
-
*/
|
|
1556
|
-
const peerOf = async (host) => {
|
|
1557
|
-
const address = (host.peer ? hostPeerAddress(host.url, { peer: host.peer }) : null) ?? (await describedPeer(host.url));
|
|
1558
|
-
return pinnedTo(address, host.host ?? host.did);
|
|
1559
|
-
};
|
|
1560
|
-
/** What each space was last told to reach, so nothing reconnects when nothing changed */
|
|
1561
|
-
const reaching = new Map();
|
|
1562
|
-
/** Gives a space's runtime the hosts to hold sockets to: the account's, and those it pays itself */
|
|
1563
|
-
async function reachHosts(spaceId, spaceHosts) {
|
|
1564
|
-
if (!config.network)
|
|
1565
|
-
return;
|
|
1566
|
-
const open = runtimes.get(spaceId);
|
|
1567
|
-
if (!open)
|
|
1568
|
-
return;
|
|
1569
|
-
const hosts = [
|
|
1570
|
-
...(await hostingRecords()),
|
|
1571
|
-
];
|
|
1572
|
-
if (spaceId === accountSpaceId)
|
|
1573
|
-
hosts.push(...(config.network.hosts ?? []).map((url) => ({ url })));
|
|
1574
|
-
// Asked only while it is still open: asking would open it again.
|
|
1575
|
-
if (!(await kindOf(spaceId)) && runtimes.get(spaceId) === open)
|
|
1576
|
-
hosts.push(...(spaceHosts ?? (await namedHosts(spaceId))));
|
|
1577
|
-
// The nodes the invite that brought it here named: the inviter's hosts, reached before the space's own
|
|
1578
|
-
// records are. Once the space names its keepers, only those of them it names: an invite is unauthenticated.
|
|
1579
|
-
const named = (await registry.get(spaceId))?.nodes ?? [];
|
|
1580
|
-
const keepers = new Set(named.length > 0
|
|
1581
|
-
? ((await (await open).access().catch(() => null))?.keepers ?? []).map((keeper) => keeper.did)
|
|
1582
|
-
: []);
|
|
1583
|
-
const invited = named.filter((node) => keepers.size === 0 || keepers.has(decodeURIComponent(node.split('#')[1] ?? '')));
|
|
1584
|
-
const peers = [
|
|
1585
|
-
...new Set([...(await Promise.all(hosts.map(peerOf))), ...invited].filter((peer) => peer !== null)),
|
|
1586
|
-
].sort();
|
|
1587
|
-
const said = peers.join(' ');
|
|
1588
|
-
if (reaching.get(spaceId) === said || runtimes.get(spaceId) !== open)
|
|
1589
|
-
return;
|
|
1590
|
-
reaching.set(spaceId, said);
|
|
1591
|
-
(await open).useNodes(peers);
|
|
1592
|
-
}
|
|
1593
|
-
const hosting = Object.freeze({
|
|
1594
|
-
async space(spaceId) {
|
|
1595
|
-
const hand = !narrowNote;
|
|
1596
|
-
const views = await Promise.all((await namedHosts(spaceId)).map((known) => askSpaceHost(spaceId, known, hand)));
|
|
1597
|
-
if (hand)
|
|
1598
|
-
spaceHostsAsked.set(spaceId, { at: Date.now(), named: views.map((v) => v.url).join(' ') });
|
|
1599
|
-
return views;
|
|
1600
|
-
},
|
|
1601
|
-
async list() {
|
|
1602
|
-
return Promise.all((await hostingRecords()).map((known) => viewHosting(known)));
|
|
1603
|
-
},
|
|
1604
|
-
async over(spaceId) {
|
|
1605
|
-
const found = [];
|
|
1606
|
-
for (const hosting of await hostingRecords()) {
|
|
1607
|
-
const status = hosting.receipt ? await readStatus(hosting.receipt, hosting.host, provider) : null;
|
|
1608
|
-
const over = status?.over?.find((one) => one.space === spaceId);
|
|
1609
|
-
if (over)
|
|
1610
|
-
found.push({ url: hosting.url, name: hosting.name ?? new URL(hosting.url).host, over });
|
|
1611
|
-
}
|
|
1612
|
-
return found;
|
|
1613
|
-
},
|
|
1614
|
-
async use(address) {
|
|
1615
|
-
const registryRt = await requireAccount('Using a host');
|
|
1616
|
-
const base = checkAddress(address, 'A host').origin;
|
|
1617
|
-
const known = (await hostingRecords()).find((existing) => existing.url === base);
|
|
1618
|
-
if (known)
|
|
1619
|
-
return viewHosting(known, true);
|
|
1620
|
-
const description = await describeHost(base);
|
|
1621
|
-
const peer = hostPeerAddress(base, description);
|
|
1622
|
-
const record = {
|
|
1623
|
-
url: base,
|
|
1624
|
-
host: description.did,
|
|
1625
|
-
name: description.name,
|
|
1626
|
-
...(peer ? { peer } : {}),
|
|
1627
|
-
seed: base64UrlEncode(newSubscriptionSeed()),
|
|
1628
|
-
since: new Date().toISOString(),
|
|
1629
|
-
};
|
|
1630
|
-
await registryRt.upsertSystem(HOSTING_COLLECTION, await hostingKey(base), record);
|
|
1631
|
-
return viewHosting(record, true);
|
|
1632
|
-
},
|
|
1633
|
-
async pay(url, payment) {
|
|
1634
|
-
return (await hostClient(await requireHosting(url))).client.pay(payment);
|
|
1635
|
-
},
|
|
1636
|
-
async remind(url, email) {
|
|
1637
|
-
await (await hostClient(await requireHosting(url))).client.remind(email);
|
|
1638
|
-
},
|
|
1639
|
-
async payForSpace(spaceId, url, payment) {
|
|
1640
|
-
return (await spaceHostClient(spaceId, url)).pay(spaceId, payment);
|
|
1641
|
-
},
|
|
1642
|
-
async remindForSpace(spaceId, url, email) {
|
|
1643
|
-
await (await spaceHostClient(spaceId, url)).remind(spaceId, email);
|
|
1644
|
-
},
|
|
1645
|
-
async stopForSpace(spaceId, url) {
|
|
1646
|
-
const named = (await namedHosts(spaceId)).find((known) => known.url === url);
|
|
1647
|
-
if (!named)
|
|
1648
|
-
throw new Error('This space doesn’t use the host at that address');
|
|
1649
|
-
// Which bots are the host's is its own word, signed: asked before it is let go.
|
|
1650
|
-
const view = await askSpaceHost(spaceId, named, false);
|
|
1651
|
-
// Un-named first, so no device hands it the key that follows.
|
|
1652
|
-
const rt = await runtime(spaceId);
|
|
1653
|
-
for (const record of await rt.list({ collection: 'std.host' })) {
|
|
1654
|
-
const body = record.body;
|
|
1655
|
-
if (record.deleted || !isRecord(body) || typeof body.url !== 'string')
|
|
1656
|
-
continue;
|
|
1657
|
-
let origin;
|
|
1658
|
-
try {
|
|
1659
|
-
origin = new URL(body.url).origin;
|
|
1660
|
-
}
|
|
1661
|
-
catch {
|
|
1662
|
-
continue;
|
|
1663
|
-
}
|
|
1664
|
-
if (origin === url)
|
|
1665
|
-
await rt.remove(record.key);
|
|
1666
|
-
}
|
|
1667
|
-
const access = await spaces.access(spaceId);
|
|
1668
|
-
const members = new Map(access.members.map((member) => [member.did, member.roles]));
|
|
1669
|
-
const bots = [];
|
|
1670
|
-
for (const bot of view.bots.map((one) => one.bot)) {
|
|
1671
|
-
const roles = members.get(bot);
|
|
1672
|
-
if (roles && (await spaces.may(spaceId, MEMBER_REMOVE, { self: false, roles })))
|
|
1673
|
-
bots.push(bot);
|
|
1674
|
-
}
|
|
1675
|
-
if (bots.length === 0 && !(await spaces.may(spaceId, KEY_CHANGE)))
|
|
1676
|
-
return { bots: [], newKey: false };
|
|
1677
|
-
for (const bot of bots)
|
|
1678
|
-
await spaces.removeMember(spaceId, bot);
|
|
1679
|
-
// A host that can't say whether it holds a pass is taken to hold one.
|
|
1680
|
-
const handed = view.status ? view.status.carrying : true;
|
|
1681
|
-
const newKey = access.key !== null && (bots.length > 0 || handed);
|
|
1682
|
-
// Removing a member changes the key by itself; with none removed it is changed here.
|
|
1683
|
-
if (newKey && bots.length === 0)
|
|
1684
|
-
await spaces.changeKey(spaceId);
|
|
1685
|
-
return { bots, newKey };
|
|
1686
|
-
},
|
|
1687
|
-
async startBot(spaceId, url, bot) {
|
|
1688
|
-
const client = await spaceHostClient(spaceId, url);
|
|
1689
|
-
const invite = await spaces.invite(spaceId, bot.role ? { role: bot.role } : {});
|
|
1690
|
-
const { bot: did, status } = await client.startBot(spaceId, bot.name, invite);
|
|
1691
|
-
return { bot: did, status };
|
|
1692
|
-
},
|
|
1693
|
-
async stop(url) {
|
|
1694
|
-
const registryRt = await requireAccount('Stopping a host');
|
|
1695
|
-
const known = await requireHosting(url);
|
|
1696
|
-
const { client } = await hostClient(known);
|
|
1697
|
-
await client.detach().catch(() => { });
|
|
1698
|
-
const carrier = (await liveCarriers()).find(({ body }) => body.did === known.host);
|
|
1699
|
-
if (carrier)
|
|
1700
|
-
await carriers.remove(carrier.carry.space.id);
|
|
1701
|
-
await registryRt.removeSystem(await hostingKey(known.url));
|
|
1702
|
-
},
|
|
1703
|
-
});
|
|
1704
|
-
// ─── Contacts ──────────────────────────────────────────────────────
|
|
1705
|
-
//
|
|
1706
|
-
// One `std.contact` per person in the contacts space, keyed by their DID, so
|
|
1707
|
-
// there is one per person on every device. Asking someone is a knock left
|
|
1708
|
-
// as a `std.contact-request` in a space you share: the signed invite to a new space for
|
|
1709
|
-
// two, sealed to their contact key, so it opens only for them, and only as
|
|
1710
|
-
// coming from the account that left it.
|
|
1711
|
-
// The key `onePer: ['did']` derives, so the record for someone is the same one on every device.
|
|
1712
|
-
const contactRecordKey = async (did) => (await contactsRuntime()).onePerKey(contactSchema.name, { did }, { onePer: contactSchema.rules.onePer });
|
|
1713
|
-
async function contactsRuntime() {
|
|
1714
|
-
if (!contactsSpaceId)
|
|
1715
|
-
throw new Error('This app was not given your contacts. Connect to your account home again, and allow contacts.');
|
|
1716
|
-
return runtime(contactsSpaceId);
|
|
1717
|
-
}
|
|
1718
|
-
/** Making and joining spaces for two needs a note good for every space — whole-account access. */
|
|
1719
|
-
function requireEverywhere(what) {
|
|
1720
|
-
// As a knock needs: `/account/write` for the whole account (spec 01 §8, 07).
|
|
1721
|
-
if (narrowNote) {
|
|
1722
|
-
throw new Error(`${what} makes or joins a space, which needs access to your whole account. Connect to your account home again, and ask for it.`);
|
|
1723
|
-
}
|
|
1724
|
-
}
|
|
1725
|
-
/** Defines a collection in a space that has none by that name yet */
|
|
1726
|
-
async function ensureDefined(open, definition) {
|
|
1727
|
-
if ((await open.collections()).some((collection) => collection.name === definition.name && collection.version !== null))
|
|
1728
|
-
return;
|
|
1729
|
-
try {
|
|
1730
|
-
await open.define(definition);
|
|
1731
|
-
}
|
|
1732
|
-
catch {
|
|
1733
|
-
throw new Error(`This space has no ${definition.title ?? definition.name} collection yet, and you can't add one here. Ask someone who manages it.`);
|
|
1734
|
-
}
|
|
1735
|
-
}
|
|
1736
|
-
async function contactRecords() {
|
|
1737
|
-
if (!contactsSpaceId)
|
|
1738
|
-
return [];
|
|
1739
|
-
const found = [];
|
|
1740
|
-
const listed = await ownRecords(await contactsRuntime(), { collection: contactSchema.name }, (record) => typeof record.body?.did === 'string' && typeof record.body.name === 'string');
|
|
1741
|
-
// One record per person, under the key their DID gives.
|
|
1742
|
-
for (const record of listed)
|
|
1743
|
-
if (record.key === (await contactRecordKey(record.body.did)))
|
|
1744
|
-
found.push(record);
|
|
1745
|
-
return found;
|
|
1746
|
-
}
|
|
1747
|
-
/** Whoever the account blocked */
|
|
1748
|
-
const blockedDids = async () => new Set((await contactRecords()).flatMap(({ body }) => (body.blocked === true ? [body.did] : [])));
|
|
1749
|
-
function requireContactKeys() {
|
|
1750
|
-
if (!contactKeys)
|
|
1751
|
-
throw new Error("This app can't read contact requests. Connect to your account home again, and allow contacts.");
|
|
1752
|
-
}
|
|
1753
|
-
function contactView(record) {
|
|
1754
|
-
const body = record.body;
|
|
1755
|
-
return Object.freeze({
|
|
1756
|
-
did: body.did,
|
|
1757
|
-
name: body.name,
|
|
1758
|
-
space: typeof body.space === 'string' ? body.space : null,
|
|
1759
|
-
...(typeof body.note === 'string' ? { note: body.note } : {}),
|
|
1760
|
-
blocked: body.blocked === true,
|
|
1761
|
-
updatedAt: record.updatedAt,
|
|
1762
|
-
});
|
|
1763
|
-
}
|
|
1764
|
-
async function writeContact(body) {
|
|
1765
|
-
const open = await contactsRuntime();
|
|
1766
|
-
await ensureDefined(open, contactSchema);
|
|
1767
|
-
// One per person: writing again is the next version of their record.
|
|
1768
|
-
return contactView(await open.put(contactSchema.name, body));
|
|
1769
|
-
}
|
|
1770
|
-
/** Leaves a space for two, unless another contact still names it */
|
|
1771
|
-
async function leavePairSpace(spaceId, did) {
|
|
1772
|
-
if (!spaceId || !(await registry.get(spaceId)))
|
|
1773
|
-
return;
|
|
1774
|
-
if ((await contactRecords()).some((record) => record.body.did !== did && record.body.space === spaceId))
|
|
1775
|
-
return;
|
|
1776
|
-
await spaces.leave(spaceId);
|
|
1777
|
-
}
|
|
1778
|
-
/**
|
|
1779
|
-
* A knock left in a space as a contact request, opened — or null when it
|
|
1780
|
-
* isn't one sealed to this account's contact key, by the account that wrote it.
|
|
1781
|
-
*/
|
|
1782
|
-
async function openMail(record) {
|
|
1783
|
-
if (!config.contactKey ||
|
|
1784
|
-
!contactKeys ||
|
|
1785
|
-
!record?.verified ||
|
|
1786
|
-
record.collection !== contactRequestSchema.name)
|
|
1787
|
-
return null;
|
|
1788
|
-
const body = record.body;
|
|
1789
|
-
if (!isRecord(body) || body.to !== contactKeys.publicKey || typeof body.sealed !== 'string')
|
|
1790
|
-
return null;
|
|
1791
|
-
const opened = await openKnock([config.contactKey], body.sealed, provider);
|
|
1792
|
-
if (!opened || opened.from !== record.root || opened.from === config.signer.did)
|
|
1793
|
-
return null;
|
|
1794
|
-
return opened;
|
|
1795
|
-
}
|
|
1796
|
-
/**
|
|
1797
|
-
* A space for two and a knock that invites someone to it, sealed to `to`:
|
|
1798
|
-
* their inbox key or their contact key. The space waits for a carrier to
|
|
1799
|
-
* hold it before the knock is made, so they can join with every device of
|
|
1800
|
-
* this account away (`spaces.carried`).
|
|
1801
|
-
*/
|
|
1802
|
-
async function makePair(to, names, note) {
|
|
1803
|
-
const pair = await spaces.create({
|
|
1804
|
-
name: `${clip(names.mine, 64)} & ${clip(names.theirs, 64)}`,
|
|
1805
|
-
visibility: 'private',
|
|
1806
|
-
...team,
|
|
1807
|
-
});
|
|
1808
|
-
try {
|
|
1809
|
-
const invite = await spaces.invite(pair.id, { role: 'editor' });
|
|
1810
|
-
const { signed, invite: secret } = parseSpaceInvite(invite);
|
|
1811
|
-
if (!secret)
|
|
1812
|
-
throw new Error('The invite to the space for two opens no role');
|
|
1813
|
-
const carried = await spaces.carried(pair.id);
|
|
1814
|
-
const sealed = await sealKnock(to, { invite: signed, secret: base64UrlDecode(secret), name: names.mine, ...(note ? { note } : {}) }, looseSigner(), provider);
|
|
1815
|
-
return { space: pair.id, invite, sealed, carried };
|
|
1816
|
-
}
|
|
1817
|
-
catch (error) {
|
|
1818
|
-
await spaces.leave(pair.id).catch(() => { });
|
|
1819
|
-
throw error;
|
|
1820
|
-
}
|
|
1821
|
-
}
|
|
1822
|
-
const contacts = Object.freeze({
|
|
1823
|
-
async space() {
|
|
1824
|
-
return contactsSpaceId;
|
|
1825
|
-
},
|
|
1826
|
-
async list() {
|
|
1827
|
-
return (await contactRecords())
|
|
1828
|
-
.map(contactView)
|
|
1829
|
-
.sort((a, b) => a.name.localeCompare(b.name) || a.did.localeCompare(b.did));
|
|
1830
|
-
},
|
|
1831
|
-
async get(did) {
|
|
1832
|
-
const record = (await contactRecords()).find((found) => found.body.did === did);
|
|
1833
|
-
return record ? contactView(record) : null;
|
|
1834
|
-
},
|
|
1835
|
-
async put(contact) {
|
|
1836
|
-
if (!contact.did.startsWith('did:'))
|
|
1837
|
-
throw new Error('A contact needs their account DID');
|
|
1838
|
-
const name = contact.name.trim().slice(0, 200);
|
|
1839
|
-
if (!name)
|
|
1840
|
-
throw new Error('A contact needs a name');
|
|
1841
|
-
return writeContact({
|
|
1842
|
-
did: contact.did,
|
|
1843
|
-
name,
|
|
1844
|
-
...(contact.space ? { space: contact.space } : {}),
|
|
1845
|
-
...(contact.note ? { note: contact.note.slice(0, 2000) } : {}),
|
|
1846
|
-
});
|
|
1847
|
-
},
|
|
1848
|
-
async remove(did) {
|
|
1849
|
-
const found = await contacts.get(did);
|
|
1850
|
-
if (!found)
|
|
1851
|
-
return;
|
|
1852
|
-
await leavePairSpace(found.space, did);
|
|
1853
|
-
const key = await contactRecordKey(did);
|
|
1854
|
-
if (key)
|
|
1855
|
-
await (await contactsRuntime()).remove(key);
|
|
1856
|
-
},
|
|
1857
|
-
async block(did) {
|
|
1858
|
-
const found = await contacts.get(did);
|
|
1859
|
-
await leavePairSpace(found?.space ?? null, did);
|
|
1860
|
-
await writeContact({
|
|
1861
|
-
did,
|
|
1862
|
-
name: found?.name ?? did,
|
|
1863
|
-
blocked: true,
|
|
1864
|
-
...(found?.note ? { note: found.note } : {}),
|
|
1865
|
-
});
|
|
1866
|
-
},
|
|
1867
|
-
async ask(spaceId, did, options = {}) {
|
|
1868
|
-
requireEverywhere('Adding a contact');
|
|
1869
|
-
if (did === config.signer.did)
|
|
1870
|
-
throw new Error('That is you');
|
|
1871
|
-
if (!contactsSpaceId)
|
|
1872
|
-
await contactsRuntime();
|
|
1873
|
-
const shared = await runtime(spaceId);
|
|
1874
|
-
const profiles = await shared.profiles();
|
|
1875
|
-
const theirs = profiles.find((profile) => profile.did === did);
|
|
1876
|
-
if (!theirs?.contactKey) {
|
|
1877
|
-
throw new Error("They can't be asked here yet: their profile in this space has no contact key. It appears once they open the space in an up-to-date app.");
|
|
1878
|
-
}
|
|
1879
|
-
const mine = (await ownName()) ?? profiles.find((profile) => profile.did === config.signer.did)?.name ?? 'Me';
|
|
1880
|
-
const note = options.note?.trim().slice(0, 2000);
|
|
1881
|
-
const made = await makePair(theirs.contactKey, { mine, theirs: theirs.name }, note);
|
|
1882
|
-
await ensureDefined(shared, contactRequestSchema);
|
|
1883
|
-
await writeContact({ did, name: theirs.name, space: made.space });
|
|
1884
|
-
const request = await shared.put(contactRequestSchema.name, {
|
|
1885
|
-
to: theirs.contactKey,
|
|
1886
|
-
sealed: made.sealed,
|
|
1887
|
-
});
|
|
1888
|
-
return { space: made.space, request: request.key, carried: made.carried };
|
|
1889
|
-
},
|
|
1890
|
-
async requests(spaceId) {
|
|
1891
|
-
requireContactKeys();
|
|
1892
|
-
const shared = await runtime(spaceId);
|
|
1893
|
-
const blocked = await blockedDids();
|
|
1894
|
-
const names = new Map((await shared.profiles()).map((profile) => [profile.did, profile.name]));
|
|
1895
|
-
const found = [];
|
|
1896
|
-
for (const record of await shared.list({ collection: contactRequestSchema.name })) {
|
|
1897
|
-
const opened = await openMail(record);
|
|
1898
|
-
if (!opened || blocked.has(opened.from))
|
|
1899
|
-
continue;
|
|
1900
|
-
// Already accepted, here or on another device.
|
|
1901
|
-
if (await registry.get(opened.pairSpace))
|
|
1902
|
-
continue;
|
|
1903
|
-
found.push({
|
|
1904
|
-
space: spaceId,
|
|
1905
|
-
key: record.key,
|
|
1906
|
-
from: opened.from,
|
|
1907
|
-
name: names.get(opened.from) ?? null,
|
|
1908
|
-
...(opened.note ? { note: opened.note } : {}),
|
|
1909
|
-
pairSpace: opened.pairSpace,
|
|
1910
|
-
createdAt: record.createdAt,
|
|
1911
|
-
});
|
|
1912
|
-
}
|
|
1913
|
-
return found;
|
|
1914
|
-
},
|
|
1915
|
-
async accept(spaceId, requestKey) {
|
|
1916
|
-
requireEverywhere('Accepting a contact request');
|
|
1917
|
-
requireContactKeys();
|
|
1918
|
-
const shared = await runtime(spaceId);
|
|
1919
|
-
const opened = await openMail(await shared.get(requestKey));
|
|
1920
|
-
if (!opened)
|
|
1921
|
-
throw new Error('That contact request is gone, or is not for you.');
|
|
1922
|
-
await spaces.join(opened.invite);
|
|
1923
|
-
const name = (await shared.profiles()).find((profile) => profile.did === opened.from)?.name ??
|
|
1924
|
-
(await contacts.get(opened.from))?.name ??
|
|
1925
|
-
opened.name;
|
|
1926
|
-
return writeContact({ did: opened.from, name, space: opened.pairSpace });
|
|
1927
|
-
},
|
|
1928
|
-
async others(did) {
|
|
1929
|
-
const found = await contacts.get(did);
|
|
1930
|
-
if (!found?.space || !(await registry.get(found.space)))
|
|
1931
|
-
return [];
|
|
1932
|
-
const open = await runtime(found.space);
|
|
1933
|
-
const [{ members }, profiles, status] = await Promise.all([
|
|
1934
|
-
open.access(),
|
|
1935
|
-
open.profiles(),
|
|
1936
|
-
open.status(),
|
|
1937
|
-
]);
|
|
1938
|
-
const seen = new Set([
|
|
1939
|
-
...members.map((member) => member.did),
|
|
1940
|
-
...profiles.map((profile) => profile.did),
|
|
1941
|
-
...Object.values(status.accounts),
|
|
1942
|
-
]);
|
|
1943
|
-
return [...seen].filter((account) => account !== config.signer.did && account !== did).sort();
|
|
1944
|
-
},
|
|
1945
|
-
});
|
|
1946
|
-
// ─── The inbox ─────────────────────────────────────────────────────
|
|
1947
|
-
//
|
|
1948
|
-
// The inbox's settings are a `std.inbox` in the contacts space; its keys
|
|
1949
|
-
// are derived from the contact key and its `gen`, so every device with the
|
|
1950
|
-
// contact key opens the same inbox. Knocks wait in the mailboxes it names.
|
|
1951
|
-
//
|
|
1952
|
-
// A knock you left is a `std.knock` until someone other than you joins
|
|
1953
|
-
// the space for two: only the holder of the inbox key could open the
|
|
1954
|
-
// invite, so whoever joins is them. Then it becomes a contact, and the
|
|
1955
|
-
// invite is closed. See `packages/core/src/inbox/inbox.ts`.
|
|
1956
|
-
/** Knocks seen in this node's inbox, by id: opened (null when they didn't check out), and until when to keep them */
|
|
1957
|
-
const knockCache = new Map();
|
|
1958
|
-
/** Knocks that didn't check out, by id, and until when they are not opened again: one dated a little ahead may pass later */
|
|
1959
|
-
const failed = new Map();
|
|
1960
|
-
const DAY_MS = 24 * 3600 * 1000;
|
|
1961
|
-
/** The inbox is the account's own, in its contacts space: only a key acting as the account opens one, as every peer checks */
|
|
1962
|
-
const inboxAllowed = () => contactsSpaceId !== null && !narrowNote;
|
|
1963
|
-
function requireContactKey(what) {
|
|
1964
|
-
// The inbox is the account's: a key whose note doesn't grant `/account/write` never opens one or knocks.
|
|
1965
|
-
if (!inboxAllowed())
|
|
1966
|
-
throw new Error(`This key's note doesn't let it use your inbox. ${what} is the person's to do.`);
|
|
1967
|
-
if (!config.contactKey)
|
|
1968
|
-
throw new Error(`${what} needs your contact key. Connect to your account home again, and allow contacts.`);
|
|
1969
|
-
return config.contactKey;
|
|
1970
|
-
}
|
|
1971
|
-
/** An inbox's keys, from the contact key and its gen */
|
|
1972
|
-
async function inboxKeys(gen) {
|
|
1973
|
-
const contactKey = requireContactKey('Your inbox');
|
|
1974
|
-
const key = await deriveInboxKeyBytes(contactKey, gen);
|
|
1975
|
-
const sign = await deriveInboxSignKeyBytes(contactKey, gen);
|
|
1976
|
-
const signPublic = contactPublicKey(sign);
|
|
1977
|
-
return { key, sign, publicKey: contactPublicKey(key), signPublic, topic: await inboxTopic(signPublic) };
|
|
1978
|
-
}
|
|
1979
|
-
/** The account's inbox: the newest `std.inbox` of the highest gen */
|
|
1980
|
-
async function inboxRecord() {
|
|
1981
|
-
if (!contactsSpaceId)
|
|
1982
|
-
return null;
|
|
1983
|
-
const records = await ownRecords(await contactsRuntime(), { collection: inboxSchema.name }, (record) => Number.isSafeInteger(record.body?.gen) && record.body.gen >= 0 && Array.isArray(record.body.places));
|
|
1984
|
-
return (records.sort((a, b) => b.body.gen - a.body.gen || b.updatedAt.localeCompare(a.updatedAt))[0] ?? null);
|
|
1985
|
-
}
|
|
1986
|
-
async function inboxView(record) {
|
|
1987
|
-
const body = record.body;
|
|
1988
|
-
const keys = await inboxKeys(body.gen);
|
|
1989
|
-
return Object.freeze({
|
|
1990
|
-
gen: body.gen,
|
|
1991
|
-
...(body.name ? { name: body.name } : {}),
|
|
1992
|
-
key: keys.publicKey,
|
|
1993
|
-
sign: keys.signPublic,
|
|
1994
|
-
places: Object.freeze([...body.places]),
|
|
1995
|
-
code: await encodeInbox(keys.sign, {
|
|
1996
|
-
key: keys.publicKey,
|
|
1997
|
-
sign: keys.signPublic,
|
|
1998
|
-
gen: body.gen,
|
|
1999
|
-
places: body.places,
|
|
2000
|
-
...(body.name ? { name: body.name } : {}),
|
|
2001
|
-
}, provider),
|
|
2002
|
-
updatedAt: record.updatedAt,
|
|
2003
|
-
});
|
|
2004
|
-
}
|
|
2005
|
-
/** Writes the inbox's settings, checked the way a knocker will read its code */
|
|
2006
|
-
async function writeInbox(body, current) {
|
|
2007
|
-
const keys = await inboxKeys(body.gen);
|
|
2008
|
-
await encodeInbox(keys.sign, { ...body, key: keys.publicKey, sign: keys.signPublic }, provider);
|
|
2009
|
-
const open = await contactsRuntime();
|
|
2010
|
-
await ensureDefined(open, inboxSchema);
|
|
2011
|
-
return inboxView(current ? await open.update(current.key, body) : await open.put(inboxSchema.name, body));
|
|
2012
|
-
}
|
|
2013
|
-
/** Clears knocks from every mailbox an inbox names that can purge, as its owner; how many did */
|
|
2014
|
-
async function purgeInbox(body, ids) {
|
|
2015
|
-
const keys = await inboxKeys(body.gen);
|
|
2016
|
-
const done = await Promise.allSettled(body.places
|
|
2017
|
-
.filter((place) => relayKind(place)?.can.purge)
|
|
2018
|
-
.map((place) => mailbox.purge(place, keys.topic, keys.signPublic, ids, (nonce) => signPurge(keys.sign, keys.topic, nonce, ids))));
|
|
2019
|
-
return done.filter((result) => result.status === 'fulfilled').length;
|
|
2020
|
-
}
|
|
2021
|
-
async function sentRecords() {
|
|
2022
|
-
if (!contactsSpaceId)
|
|
2023
|
-
return [];
|
|
2024
|
-
return ownRecords(await contactsRuntime(), { collection: knockSchema.name }, (record) => typeof record.body?.space === 'string' && typeof record.body.invite === 'string');
|
|
2025
|
-
}
|
|
2026
|
-
/**
|
|
2027
|
-
* Knocks of yours: one someone joined becomes a contact, and its invite is
|
|
2028
|
-
* closed; one nobody joined within the knock's life is let go, space and all.
|
|
2029
|
-
*/
|
|
2030
|
-
async function settleSent() {
|
|
2031
|
-
for (const record of await sentRecords()) {
|
|
2032
|
-
const { space, name, invite } = record.body;
|
|
2033
|
-
if (!(await registry.get(space))) {
|
|
2034
|
-
await (await contactsRuntime()).remove(record.key);
|
|
2035
|
-
continue;
|
|
2036
|
-
}
|
|
2037
|
-
const open = await runtime(space);
|
|
2038
|
-
// Only the holder of the inbox key could open the invite: whoever joined first is them.
|
|
2039
|
-
const joiner = (await open.access()).members.find((member) => member.did !== config.signer.did)?.did;
|
|
2040
|
-
if (joiner) {
|
|
2041
|
-
// Whoever else the invite reached, nobody more joins with it.
|
|
2042
|
-
await spaces.closeInvite(space, invite).catch(() => { });
|
|
2043
|
-
const given = (await open.profiles()).find((profile) => profile.did === joiner)?.name;
|
|
2044
|
-
await writeContact({ did: joiner, name: given ?? name, space });
|
|
2045
|
-
await (await contactsRuntime()).remove(record.key);
|
|
2046
|
-
}
|
|
2047
|
-
else if (Date.now() - Date.parse(record.createdAt) > KNOCK_TTL_SECONDS * 1000 + DAY_MS) {
|
|
2048
|
-
await spaces.leave(space).catch(() => { });
|
|
2049
|
-
await (await contactsRuntime()).remove(record.key);
|
|
2050
|
-
}
|
|
2051
|
-
}
|
|
2052
|
-
}
|
|
2053
|
-
/** What the mailboxes of this node's inbox hold now, opened and cached */
|
|
2054
|
-
async function readKnocks() {
|
|
2055
|
-
const now = Date.now();
|
|
2056
|
-
for (const [id, cached] of knockCache)
|
|
2057
|
-
if (cached.until <= now)
|
|
2058
|
-
knockCache.delete(id);
|
|
2059
|
-
const record = await inboxRecord();
|
|
2060
|
-
if (!record)
|
|
2061
|
-
return [];
|
|
2062
|
-
const { gen, places } = record.body;
|
|
2063
|
-
const keys = await inboxKeys(gen);
|
|
2064
|
-
// Every mailbox, in full: an inbox holds 64 knocks at most, and a knock
|
|
2065
|
-
// cleared from another device should go from here too. What was opened
|
|
2066
|
-
// once is not opened again, nor what failed to.
|
|
2067
|
-
const held = new Map();
|
|
2068
|
-
const fetched = await Promise.allSettled(places.map((place) => mailbox.fetch(place, keys.topic)));
|
|
2069
|
-
for (const result of fetched) {
|
|
2070
|
-
if (result.status !== 'fulfilled')
|
|
2071
|
-
continue;
|
|
2072
|
-
// A relay's id is only its word: file the knock under the hash of what it is.
|
|
2073
|
-
for (const item of result.value)
|
|
2074
|
-
held.set(await knockId(item.blob), item.blob);
|
|
2075
|
-
}
|
|
2076
|
-
const found = [];
|
|
2077
|
-
for (const [id, blob] of held) {
|
|
2078
|
-
let opened = knockCache.get(id)?.opened ?? null;
|
|
2079
|
-
if (!opened && (failed.get(id) ?? 0) <= now) {
|
|
2080
|
-
opened = await openKnock([keys.key], blob, provider);
|
|
2081
|
-
if (opened)
|
|
2082
|
-
knockCache.set(id, { opened, until: opened.at + KNOCK_TTL_SECONDS * 1000 });
|
|
2083
|
-
else
|
|
2084
|
-
failed.set(id, now + 15 * 60_000);
|
|
2085
|
-
}
|
|
2086
|
-
if (opened)
|
|
2087
|
-
found.push({ id, opened });
|
|
2088
|
-
}
|
|
2089
|
-
return found;
|
|
2090
|
-
}
|
|
2091
|
-
/** A direct message as this account reads it — null when it is neither by nor for this account */
|
|
2092
|
-
async function directView(spaceId, open, record) {
|
|
2093
|
-
// Who wrote it is whoever created it: the context binds that account, so a copy posted by anyone else opens nothing.
|
|
2094
|
-
const from = record.createdBy;
|
|
2095
|
-
if (!record.verified || record.collection !== directSchema.name || !from || record.root !== from)
|
|
2096
|
-
return null;
|
|
2097
|
-
const to = Array.isArray(record.body?.to) ? record.body.to.filter((did) => typeof did === 'string') : [];
|
|
2098
|
-
const me = config.signer.did;
|
|
2099
|
-
if (from !== me && !to.includes(me))
|
|
2100
|
-
return null;
|
|
2101
|
-
const pair = open.ownMemberKey();
|
|
2102
|
-
const opened = pair ? await openDirect(spaceId, from, record.body, me, pair) : null;
|
|
2103
|
-
return Object.freeze({
|
|
2104
|
-
key: record.key,
|
|
2105
|
-
from,
|
|
2106
|
-
to: [...to].sort(),
|
|
2107
|
-
text: opened?.text ?? null,
|
|
2108
|
-
createdAt: record.createdAt,
|
|
2109
|
-
...(record.recordsOnly ? { recordsOnly: true } : {}),
|
|
2110
|
-
});
|
|
2111
|
-
}
|
|
2112
|
-
const direct = Object.freeze({
|
|
2113
|
-
async reachable(spaceId) {
|
|
2114
|
-
const open = await runtime(spaceId);
|
|
2115
|
-
const { members } = await open.access();
|
|
2116
|
-
const keys = await open.memberKeys();
|
|
2117
|
-
return members
|
|
2118
|
-
.map((member) => member.did)
|
|
2119
|
-
.filter((did) => did !== config.signer.did && keys.has(did))
|
|
2120
|
-
.sort();
|
|
2121
|
-
},
|
|
2122
|
-
async send(spaceId, to, text) {
|
|
2123
|
-
const open = await runtime(spaceId);
|
|
2124
|
-
const pair = open.ownMemberKey();
|
|
2125
|
-
if (!pair)
|
|
2126
|
-
throw new Error("This node can't seal direct messages here: it wasn't given your member key for this space.");
|
|
2127
|
-
const trimmed = text.trim();
|
|
2128
|
-
if (!trimmed)
|
|
2129
|
-
throw new Error('A direct message needs some text');
|
|
2130
|
-
// Your own key as this node holds it, so your other devices read what you sent even before it is published.
|
|
2131
|
-
const keys = new Map(await open.memberKeys());
|
|
2132
|
-
keys.set(config.signer.did, pair.publicKey);
|
|
2133
|
-
const body = await sealDirect(spaceId, config.signer.did, to, { text: trimmed }, keys);
|
|
2134
|
-
await ensureDefined(open, directSchema);
|
|
2135
|
-
const record = await open.put(directSchema.name, body);
|
|
2136
|
-
const view = await directView(spaceId, open, record);
|
|
2137
|
-
if (!view)
|
|
2138
|
-
throw new Error('The direct message was written, but could not be read back');
|
|
2139
|
-
return view;
|
|
2140
|
-
},
|
|
2141
|
-
async list(spaceId) {
|
|
2142
|
-
const open = await runtime(spaceId);
|
|
2143
|
-
const found = [];
|
|
2144
|
-
for (const record of await open.list({ collection: directSchema.name })) {
|
|
2145
|
-
const view = await directView(spaceId, open, record);
|
|
2146
|
-
if (view)
|
|
2147
|
-
found.push(view);
|
|
2148
|
-
}
|
|
2149
|
-
return found.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.key.localeCompare(b.key));
|
|
2150
|
-
},
|
|
2151
|
-
});
|
|
2152
|
-
const inbox = Object.freeze({
|
|
2153
|
-
async get() {
|
|
2154
|
-
if (!config.contactKey || !inboxAllowed())
|
|
2155
|
-
return null;
|
|
2156
|
-
const record = await inboxRecord();
|
|
2157
|
-
return record ? inboxView(record) : null;
|
|
2158
|
-
},
|
|
2159
|
-
async open(options = {}) {
|
|
2160
|
-
requireContactKey('Opening your inbox');
|
|
2161
|
-
if (!contactsSpaceId)
|
|
2162
|
-
await contactsRuntime();
|
|
2163
|
-
const current = await inboxRecord();
|
|
2164
|
-
const places = [...(options.places ?? current?.body?.places ?? usableRelays(config.network))].slice(0, MAX_INBOX_PLACES);
|
|
2165
|
-
if (places.length === 0)
|
|
2166
|
-
throw new Error('An inbox needs a mailbox to hold its knocks, and this node has none.');
|
|
2167
|
-
const name = clip((options.name ?? current?.body?.name ?? (await ownName()) ?? '').trim(), 64);
|
|
2168
|
-
return writeInbox({ gen: current?.body?.gen ?? 0, places, ...(name ? { name } : {}) }, current);
|
|
2169
|
-
},
|
|
2170
|
-
async rotate() {
|
|
2171
|
-
requireContactKey('Replacing your inbox');
|
|
2172
|
-
const current = await inboxRecord();
|
|
2173
|
-
if (!current)
|
|
2174
|
-
return inbox.open();
|
|
2175
|
-
// What waits in the old one goes with it.
|
|
2176
|
-
await purgeInbox(current.body, null).catch(() => 0);
|
|
2177
|
-
knockCache.clear();
|
|
2178
|
-
failed.clear();
|
|
2179
|
-
return writeInbox({ ...current.body, gen: current.body.gen + 1 }, current);
|
|
2180
|
-
},
|
|
2181
|
-
async clear() {
|
|
2182
|
-
requireContactKey('Clearing your inbox');
|
|
2183
|
-
const current = await inboxRecord();
|
|
2184
|
-
if (!current)
|
|
2185
|
-
throw new Error('Your inbox is not open');
|
|
2186
|
-
if ((await purgeInbox(current.body, null)) === 0)
|
|
2187
|
-
throw new Error("None of your inbox's mailboxes could be reached and cleared.");
|
|
2188
|
-
knockCache.clear();
|
|
2189
|
-
failed.clear();
|
|
2190
|
-
},
|
|
2191
|
-
async knock(code, options = {}) {
|
|
2192
|
-
requireContactKey('Knocking');
|
|
2193
|
-
requireEverywhere('Knocking');
|
|
2194
|
-
const theirs = await readInboxCode(code, provider);
|
|
2195
|
-
if ((await inbox.get())?.key === theirs.key)
|
|
2196
|
-
throw new Error('That is your own inbox');
|
|
2197
|
-
if (!contactsSpaceId)
|
|
2198
|
-
await contactsRuntime();
|
|
2199
|
-
const mine = (await ownName()) ?? 'Someone';
|
|
2200
|
-
const name = theirs.name ?? 'Contact';
|
|
2201
|
-
const made = await makePair(theirs.key, { mine, theirs: name }, options.note);
|
|
2202
|
-
const topic = await inboxTopic(theirs.sign);
|
|
2203
|
-
const left = await Promise.allSettled(theirs.places.map((place) => mailbox.drop(place, topic, made.sealed, KNOCK_TTL_SECONDS)));
|
|
2204
|
-
if (!left.some((result) => result.status === 'fulfilled')) {
|
|
2205
|
-
await spaces.leave(made.space).catch(() => { });
|
|
2206
|
-
const reasons = left
|
|
2207
|
-
.map((result) => (result.status === 'rejected' ? reasonText(result.reason) : ''))
|
|
2208
|
-
.filter(Boolean);
|
|
2209
|
-
throw new Error(`None of their inbox's mailboxes took the knock. ${reasons.join('; ')}`);
|
|
2210
|
-
}
|
|
2211
|
-
const open = await contactsRuntime();
|
|
2212
|
-
await ensureDefined(open, knockSchema);
|
|
2213
|
-
await open.put(knockSchema.name, { space: made.space, name, invite: made.invite });
|
|
2214
|
-
return { space: made.space, carried: made.carried };
|
|
2215
|
-
},
|
|
2216
|
-
async knocks() {
|
|
2217
|
-
requireContactKey('Reading knocks');
|
|
2218
|
-
await settleSent().catch(() => { });
|
|
2219
|
-
const blocked = await blockedDids();
|
|
2220
|
-
const found = [];
|
|
2221
|
-
for (const { id, opened } of await readKnocks()) {
|
|
2222
|
-
if (opened.from === config.signer.did || blocked.has(opened.from))
|
|
2223
|
-
continue;
|
|
2224
|
-
// Already accepted, here or on another device.
|
|
2225
|
-
if (await registry.get(opened.pairSpace))
|
|
2226
|
-
continue;
|
|
2227
|
-
found.push(Object.freeze({
|
|
2228
|
-
id,
|
|
2229
|
-
from: opened.from,
|
|
2230
|
-
name: opened.name,
|
|
2231
|
-
...(opened.note ? { note: opened.note } : {}),
|
|
2232
|
-
pairSpace: opened.pairSpace,
|
|
2233
|
-
at: new Date(opened.at).toISOString(),
|
|
2234
|
-
}));
|
|
2235
|
-
}
|
|
2236
|
-
return found.sort((a, b) => b.at.localeCompare(a.at));
|
|
2237
|
-
},
|
|
2238
|
-
async sent() {
|
|
2239
|
-
await settleSent().catch(() => { });
|
|
2240
|
-
return (await sentRecords()).map((record) => Object.freeze({ space: record.body.space, name: record.body.name, at: record.createdAt }));
|
|
2241
|
-
},
|
|
2242
|
-
async accept(id) {
|
|
2243
|
-
requireContactKey('Accepting a knock');
|
|
2244
|
-
requireEverywhere('Accepting a knock');
|
|
2245
|
-
if (!knockCache.get(id)?.opened)
|
|
2246
|
-
await readKnocks();
|
|
2247
|
-
const knocked = knockCache.get(id)?.opened;
|
|
2248
|
-
if (!knocked)
|
|
2249
|
-
throw new Error('That knock is gone: it expired, or your inbox was cleared or replaced.');
|
|
2250
|
-
await spaces.join(knocked.invite);
|
|
2251
|
-
const known = await contacts.get(knocked.from);
|
|
2252
|
-
const contact = await writeContact({
|
|
2253
|
-
did: knocked.from,
|
|
2254
|
-
name: known?.name ?? knocked.name,
|
|
2255
|
-
space: knocked.pairSpace,
|
|
2256
|
-
});
|
|
2257
|
-
// Done with: nobody needs it in the mailboxes any more.
|
|
2258
|
-
const current = await inboxRecord();
|
|
2259
|
-
if (current)
|
|
2260
|
-
await purgeInbox(current.body, [id]).catch(() => 0);
|
|
2261
|
-
knockCache.delete(id);
|
|
2262
|
-
return contact;
|
|
2263
|
-
},
|
|
2264
|
-
async dismiss(id) {
|
|
2265
|
-
requireContactKey('Dismissing a knock');
|
|
2266
|
-
const current = await inboxRecord();
|
|
2267
|
-
if (current)
|
|
2268
|
-
await purgeInbox(current.body, [id]);
|
|
2269
|
-
knockCache.delete(id);
|
|
2270
|
-
},
|
|
2271
|
-
});
|
|
672
|
+
const records = createNodeRecords(ctx);
|
|
2272
673
|
const collections = Object.freeze({
|
|
2273
674
|
list: perSpace((rt) => rt.collections()),
|
|
2274
675
|
define: perSpace((rt, definition) => rt.define(definition)),
|
|
2275
676
|
delete: perSpace((rt, name) => rt.undefine(name)),
|
|
2276
677
|
tag: perSpace((rt, collection, field, value) => rt.topicTag(collection, field, value)),
|
|
2277
678
|
});
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
if (!trimmed)
|
|
2284
|
-
throw new Error('A name cannot be empty');
|
|
2285
|
-
const avatar = (await ownProfile())?.avatar;
|
|
2286
|
-
const written = await registryRt.upsertSystem(PROFILE_COLLECTION, PROFILE_KEY, {
|
|
2287
|
-
name: trimmed,
|
|
2288
|
-
...(avatar ? { avatar } : {}),
|
|
2289
|
-
});
|
|
2290
|
-
emit({ type: 'account' });
|
|
2291
|
-
await publishProfileToOpenSpaces();
|
|
2292
|
-
return { name: trimmed, updatedAt: written.updatedAt, ...(avatar ? { avatar } : {}) };
|
|
2293
|
-
},
|
|
2294
|
-
async setAvatar(image, options = {}) {
|
|
2295
|
-
const registryRt = await requireAccount('Changing the picture across devices');
|
|
2296
|
-
const name = (await ownName()) ?? options.name?.trim();
|
|
2297
|
-
if (!name)
|
|
2298
|
-
throw new Error('Give the account a name first');
|
|
2299
|
-
if (image && !image.mime.startsWith('image/'))
|
|
2300
|
-
throw new Error('A picture is an image');
|
|
2301
|
-
const avatar = image ? { ...(await registryRt.addFile(image.bytes)), mime: image.mime } : null;
|
|
2302
|
-
const written = await registryRt.upsertSystem(PROFILE_COLLECTION, PROFILE_KEY, {
|
|
2303
|
-
name,
|
|
2304
|
-
...(avatar ? { avatar } : {}),
|
|
2305
|
-
});
|
|
2306
|
-
emit({ type: 'account' });
|
|
2307
|
-
await publishProfileToOpenSpaces();
|
|
2308
|
-
return { name, updatedAt: written.updatedAt, ...(avatar ? { avatar } : {}) };
|
|
2309
|
-
},
|
|
2310
|
-
async picture() {
|
|
2311
|
-
const avatar = (await ownProfile())?.avatar;
|
|
2312
|
-
if (!avatar || !accountSpaceId)
|
|
2313
|
-
return null;
|
|
2314
|
-
return { bytes: await (await runtime(accountSpaceId)).readFile(avatar), mime: avatar.mime };
|
|
2315
|
-
},
|
|
2316
|
-
revoke: async (key, options) => (await requireAccount('Revoking in the account registry')).revoke(key, options),
|
|
2317
|
-
});
|
|
2318
|
-
/** The records namespace, writing as `as` when given: an agent's key and note */
|
|
2319
|
-
function makeRecords(as) {
|
|
2320
|
-
const self = Object.freeze({
|
|
2321
|
-
list: async (spaceId, options) => (await runtime(spaceId)).list(options),
|
|
2322
|
-
get: async (spaceId, key) => (await runtime(spaceId)).get(key),
|
|
2323
|
-
contracts: async (spaceId, key, version) => (await runtime(spaceId)).contracts(key, version),
|
|
2324
|
-
keyFor: async (spaceId, name, account) => (await runtime(spaceId)).keyFor(name, account),
|
|
2325
|
-
onePerKey: async (spaceId, collection, body, options) => (await runtime(spaceId)).onePerKey(collection, body, options),
|
|
2326
|
-
put: async (spaceId, collection, body, options) => (await runtime(spaceId)).put(nameOf(collection), body, as ? { ...options, as } : options),
|
|
2327
|
-
update: async (spaceId, key, body, options) => (await runtime(spaceId)).update(key, body, as ? { ...options, as } : options),
|
|
2328
|
-
linked: async (spaceId, key, options) => (await runtime(spaceId)).linked(key, options),
|
|
2329
|
-
delete: async (spaceId, key) => (await runtime(spaceId)).remove(key, as ? { as } : undefined),
|
|
2330
|
-
history: async (spaceId, key) => (await runtime(spaceId)).history(key),
|
|
2331
|
-
addFile: async (spaceId, bytes, about) => ({
|
|
2332
|
-
...(await (await runtime(spaceId)).addFile(bytes)),
|
|
2333
|
-
mime: about.mime,
|
|
2334
|
-
...(about.name !== undefined ? { name: about.name } : {}),
|
|
2335
|
-
}),
|
|
2336
|
-
readFile: async (spaceId, ref) => (await runtime(spaceId)).readFile(ref),
|
|
2337
|
-
can: perSpace((rt, action, target) => rt.can(action, target)),
|
|
2338
|
-
async query(spaceId, query) {
|
|
2339
|
-
const space = await runtime(spaceId);
|
|
2340
|
-
// Asked before running, so a node holding part of the space starts fetching what it lacks.
|
|
2341
|
-
const complete = space.use(collectionsOf(plainQuery(query)));
|
|
2342
|
-
const result = await runQuery({
|
|
2343
|
-
list: (collection) => space.list({ collection }),
|
|
2344
|
-
get: (key) => space.get(key),
|
|
2345
|
-
linked: (key, options) => space.linked(key, options),
|
|
2346
|
-
computed: (collection) => space.computed(collection),
|
|
2347
|
-
}, query);
|
|
2348
|
-
// The query's type says what it finds; running it can't prove that.
|
|
2349
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- typed from the query
|
|
2350
|
-
return { ...result, complete };
|
|
2351
|
-
},
|
|
2352
|
-
watch(spaceId, query, onResult, onError) {
|
|
2353
|
-
let stopped = false;
|
|
2354
|
-
// Changes arrive in bursts during sync: one run at a time, never a queue of stale runs.
|
|
2355
|
-
const run = serial(async () => {
|
|
2356
|
-
if (stopped)
|
|
2357
|
-
return;
|
|
2358
|
-
try {
|
|
2359
|
-
const result = await self.query(spaceId, query);
|
|
2360
|
-
if (!stopped)
|
|
2361
|
-
onResult(result);
|
|
2362
|
-
}
|
|
2363
|
-
catch (error) {
|
|
2364
|
-
if (!stopped)
|
|
2365
|
-
onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
2366
|
-
}
|
|
2367
|
-
});
|
|
2368
|
-
const unsubscribe = events.subscribe((event) => {
|
|
2369
|
-
if (event.type === 'records' && event.space === spaceId)
|
|
2370
|
-
void run();
|
|
2371
|
-
});
|
|
2372
|
-
void run();
|
|
2373
|
-
return () => {
|
|
2374
|
-
stopped = true;
|
|
2375
|
-
unsubscribe();
|
|
2376
|
-
};
|
|
2377
|
-
},
|
|
2378
|
-
});
|
|
2379
|
-
return self;
|
|
679
|
+
// With an account key, start following the registry at once: it is how this
|
|
680
|
+
// node learns which spaces it belongs to.
|
|
681
|
+
if (accountSpaceId) {
|
|
682
|
+
await runtime(accountSpaceId);
|
|
683
|
+
await reconcile();
|
|
2380
684
|
}
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
const { note } = checked;
|
|
2389
|
-
if (!grantsRecordsOnly(note))
|
|
2390
|
-
throw new Error('That note grants more than records — ask the account home for one with `recordsOnly: true`.');
|
|
2391
|
-
if (note.payload.aud !== agentDid)
|
|
2392
|
-
throw new Error('That note was made out to a different key.');
|
|
2393
|
-
if (note.payload.iss !== config.signer.did)
|
|
2394
|
-
throw new Error('That note is from a different account.');
|
|
2395
|
-
// The spaces its note names; all of them for an agent granted the whole account.
|
|
2396
|
-
// What it may do there is its note's to say; this node also refuses, by the label, what needs a person.
|
|
2397
|
-
const reach = noteSpaces(note);
|
|
2398
|
-
const named = new Set(reach === 'all' ? [] : reach);
|
|
2399
|
-
const allowed = (spaceId) => reach === 'all' || (typeof spaceId === 'string' && named.has(spaceId));
|
|
2400
|
-
const contactsGiven = () => contactsSpaceId !== null && allowed(contactsSpaceId);
|
|
2401
|
-
// Written with the agent's key, under its note.
|
|
2402
|
-
const writes = makeRecords({ did: agentDid, key: agent.keys.privateKey, proof: () => note });
|
|
2403
|
-
// What the table in `node/api.ts` marks `own`; the rest it decides there.
|
|
2404
|
-
const own = {
|
|
2405
|
-
spaces: {
|
|
2406
|
-
list: async () => (await spaces.list()).filter((space) => allowed(space.id)),
|
|
2407
|
-
get: async (spaceId) => (allowed(spaceId) ? spaces.get(spaceId) : null),
|
|
2408
|
-
authenticator: async () => null,
|
|
2409
|
-
},
|
|
2410
|
-
records: {
|
|
2411
|
-
can: async (spaceId, action, target) => allowed(spaceId) && records.can(spaceId, action, target),
|
|
2412
|
-
watch: (spaceId, query, onResult, onError) => {
|
|
2413
|
-
if (allowed(spaceId))
|
|
2414
|
-
return records.watch(spaceId, query, onResult, onError);
|
|
2415
|
-
onError?.(new Error('The agent was not given this space.'));
|
|
2416
|
-
return () => { };
|
|
2417
|
-
},
|
|
2418
|
-
},
|
|
2419
|
-
// The runtime refuses this too, and every peer ignores it — said early, with what to do instead.
|
|
2420
|
-
collections: {
|
|
2421
|
-
define: async () => {
|
|
2422
|
-
throw new Error(CANNOT_DEFINE);
|
|
2423
|
-
},
|
|
2424
|
-
},
|
|
2425
|
-
hosting: {
|
|
2426
|
-
space: async (spaceId) => {
|
|
2427
|
-
if (!allowed(spaceId))
|
|
2428
|
-
throw new Error('That space was not given to this agent');
|
|
2429
|
-
return hosting.space(spaceId);
|
|
2430
|
-
},
|
|
2431
|
-
over: async (spaceId) => (allowed(spaceId) ? hosting.over(spaceId) : []),
|
|
2432
|
-
},
|
|
2433
|
-
contacts: {
|
|
2434
|
-
space: async () => (contactsGiven() ? contactsSpaceId : null),
|
|
2435
|
-
list: async () => (contactsGiven() ? contacts.list() : []),
|
|
2436
|
-
get: async (did) => (contactsGiven() ? contacts.get(did) : null),
|
|
2437
|
-
},
|
|
2438
|
-
direct: { reachable: async (spaceId) => (allowed(spaceId) ? direct.reachable(spaceId) : []) },
|
|
2439
|
-
inbox: { get: async () => null },
|
|
2440
|
-
};
|
|
2441
|
-
const person = (what) => async () => {
|
|
2442
|
-
throw new Error(`An agent can't ${what}. Ask the person to do it.`);
|
|
2443
|
-
};
|
|
2444
|
-
return Object.freeze({
|
|
2445
|
-
did: config.signer.did,
|
|
2446
|
-
sessionDid: agentDid,
|
|
2447
|
-
...buildNamespaces((namespace, name, policy) => {
|
|
2448
|
-
if (policy === 'own')
|
|
2449
|
-
return givenFor(own, namespace, name);
|
|
2450
|
-
const source = namespace === 'records' ? writes : Reflect.get(node, namespace);
|
|
2451
|
-
if (!isRecord(source))
|
|
2452
|
-
throw new Error(`A node has no ${namespace}`);
|
|
2453
|
-
if (policy === 'pass')
|
|
2454
|
-
return (...args) => callMethod(source, name, args);
|
|
2455
|
-
if (policy !== 'scoped')
|
|
2456
|
-
return person(policy);
|
|
2457
|
-
return async (...args) => {
|
|
2458
|
-
if (!allowed(args[0]))
|
|
2459
|
-
throw new Error('The agent was not given this space. The person can give it more in their account home.');
|
|
2460
|
-
return callMethod(source, name, args);
|
|
2461
|
-
};
|
|
2462
|
-
}),
|
|
2463
|
-
delegation: () => note,
|
|
2464
|
-
iceServers: () => node.iceServers(),
|
|
2465
|
-
asAgent: person('start another agent'),
|
|
2466
|
-
revokeKey: person('revoke a key'),
|
|
2467
|
-
revokeSelf: person('sign the account out'),
|
|
2468
|
-
subscribe: (listener) => node.subscribe((event) => {
|
|
2469
|
-
if (!('space' in event) || allowed(event.space))
|
|
2470
|
-
listener(event);
|
|
2471
|
-
}),
|
|
2472
|
-
// The agent stops; the node it acts through keeps running.
|
|
2473
|
-
close: async () => { },
|
|
2474
|
-
});
|
|
685
|
+
async function anyoneOnline() {
|
|
686
|
+
for (const open of runtimes.values()) {
|
|
687
|
+
const rt = await open.catch(() => null);
|
|
688
|
+
if (rt && (await rt.status()).peers.length > 0)
|
|
689
|
+
return true;
|
|
690
|
+
}
|
|
691
|
+
return false;
|
|
2475
692
|
}
|
|
2476
693
|
const node = Object.freeze({
|
|
2477
694
|
did: config.signer.did,
|
|
@@ -2479,14 +696,14 @@ export async function createNode(config) {
|
|
|
2479
696
|
spaces,
|
|
2480
697
|
records,
|
|
2481
698
|
collections,
|
|
2482
|
-
account:
|
|
2483
|
-
carriers,
|
|
2484
|
-
hosting,
|
|
2485
|
-
automations,
|
|
2486
|
-
contacts,
|
|
2487
|
-
direct,
|
|
2488
|
-
inbox,
|
|
2489
|
-
asAgent,
|
|
699
|
+
account: people.account,
|
|
700
|
+
carriers: carrying.carriers,
|
|
701
|
+
hosting: hosts.hosting,
|
|
702
|
+
automations: carrying.automations,
|
|
703
|
+
contacts: people.contacts,
|
|
704
|
+
direct: createNodeDirect(ctx),
|
|
705
|
+
inbox: people.inbox,
|
|
706
|
+
asAgent: (agent) => startAgent(node, agent, ctx),
|
|
2490
707
|
delegation: () => current,
|
|
2491
708
|
iceServers: async () => (mesh ? mesh.iceServers() : (config.network?.iceServers ?? DEFAULT_ICE_SERVERS)),
|
|
2492
709
|
network: Object.freeze({
|
|
@@ -2499,7 +716,7 @@ export async function createNode(config) {
|
|
|
2499
716
|
const ids = options.spaces ?? [
|
|
2500
717
|
...new Set([
|
|
2501
718
|
...(await spaces.list()).filter((space) => space.writable).map((space) => space.id),
|
|
2502
|
-
...(await carrierRecords()).map(({ carry }) => carry.space.id),
|
|
719
|
+
...(await carrying.carrierRecords()).map(({ carry }) => carry.space.id),
|
|
2503
720
|
...(contactsSpaceId ? [contactsSpaceId] : []),
|
|
2504
721
|
]),
|
|
2505
722
|
];
|
|
@@ -2513,19 +730,10 @@ export async function createNode(config) {
|
|
|
2513
730
|
return taken.every(Boolean);
|
|
2514
731
|
},
|
|
2515
732
|
async revokeSelf(options = {}) {
|
|
2516
|
-
// Forgotten first: a tab closed while the revokes wait must not leave a
|
|
2517
|
-
// revoked key behind, to be claimed and refused on every write after.
|
|
733
|
+
// Forgotten first: a tab closed while the revokes wait must not leave a revoked key to be claimed.
|
|
2518
734
|
await claimed?.forget().catch(() => { });
|
|
2519
|
-
// With
|
|
2520
|
-
|
|
2521
|
-
// person signing out looking at a spinner: they go out with the next sync.
|
|
2522
|
-
let anyone = false;
|
|
2523
|
-
for (const open of runtimes.values()) {
|
|
2524
|
-
const rt = await open.catch(() => null);
|
|
2525
|
-
if (rt && (await rt.status()).peers.length > 0)
|
|
2526
|
-
anyone = true;
|
|
2527
|
-
}
|
|
2528
|
-
await node.revokeKey(sessionDid, anyone ? options : {});
|
|
735
|
+
// With nobody online, waiting would only show a spinner: the revokes go out with the next sync.
|
|
736
|
+
await node.revokeKey(sessionDid, (await anyoneOnline()) ? options : {});
|
|
2529
737
|
},
|
|
2530
738
|
async close() {
|
|
2531
739
|
if (closed)
|
|
@@ -2534,7 +742,7 @@ export async function createNode(config) {
|
|
|
2534
742
|
stopWatchingNetwork?.();
|
|
2535
743
|
if (renewTimer)
|
|
2536
744
|
clearTimeout(renewTimer);
|
|
2537
|
-
|
|
745
|
+
carrying.stop();
|
|
2538
746
|
const open = [...runtimes.keys()];
|
|
2539
747
|
await Promise.all(open.map((spaceId) => closeRuntime(spaceId)));
|
|
2540
748
|
// Let go of the registry too: an open database connection blocks the
|