techne-sdk 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +48 -2
  3. package/dist/auth/app-key.d.ts +8 -0
  4. package/dist/auth/app-key.js +95 -0
  5. package/dist/auth/index.d.ts +192 -0
  6. package/dist/auth/index.js +230 -0
  7. package/dist/auth/placement.gen.d.ts +1 -0
  8. package/dist/auth/placement.gen.js +50 -0
  9. package/dist/catalog/catalog.gen.js +2161 -681
  10. package/dist/connect.js +2 -1
  11. package/dist/generated/index.d.ts +61 -0
  12. package/dist/generated/index.js +116 -0
  13. package/dist/generated/lexicons.d.ts +3689 -1449
  14. package/dist/generated/lexicons.js +1237 -42
  15. package/dist/generated/nsid.d.ts +23 -1
  16. package/dist/generated/nsid.js +23 -19
  17. package/dist/generated/nsid.json +23 -19
  18. package/dist/generated/records.d.ts +28 -26
  19. package/dist/generated/types/pub/techne/draft/commons/getVersions.d.ts +3 -3
  20. package/dist/generated/types/pub/techne/draft/commons/runChain.d.ts +1 -1
  21. package/dist/generated/types/pub/techne/draft/credential.d.ts +1 -1
  22. package/dist/generated/types/pub/techne/draft/credentialRevocation.d.ts +1 -1
  23. package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.d.ts +5 -0
  24. package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.js +7 -0
  25. package/dist/generated/types/pub/techne/draft/permissioned/getRecord.d.ts +2 -1
  26. package/dist/generated/types/pub/techne/draft/permissioned/listChanges.d.ts +1 -1
  27. package/dist/generated/types/pub/techne/draft/permissioned/putRecord.d.ts +2 -2
  28. package/dist/generated/types/pub/techne/draft/provenance.d.ts +1 -1
  29. package/dist/generated/types/pub/techne/draft/publisher.d.ts +1 -1
  30. package/dist/generated/types/pub/techne/draft/query/composeRecords.d.ts +152 -0
  31. package/dist/generated/types/pub/techne/draft/query/composeRecords.js +55 -0
  32. package/dist/generated/types/pub/techne/draft/query/getRecords.d.ts +1 -1
  33. package/dist/generated/types/pub/techne/draft/query/listRecords.d.ts +0 -4
  34. package/dist/generated/types/pub/techne/draft/query/listRejections.d.ts +2 -2
  35. package/dist/generated/types/pub/techne/draft/registry/blockIndex.d.ts +42 -0
  36. package/dist/generated/types/pub/techne/draft/registry/blockIndex.js +34 -0
  37. package/dist/generated/types/pub/techne/draft/registry/defs.d.ts +112 -0
  38. package/dist/generated/types/pub/techne/draft/registry/defs.js +32 -0
  39. package/dist/generated/types/pub/techne/draft/registry/getType.d.ts +23 -0
  40. package/dist/generated/types/pub/techne/draft/registry/getType.js +20 -0
  41. package/dist/generated/types/pub/techne/draft/registry/getTypeRequest.d.ts +23 -0
  42. package/dist/generated/types/pub/techne/draft/registry/getTypeRequest.js +20 -0
  43. package/dist/generated/types/pub/techne/draft/registry/listTypeRequests.d.ts +27 -0
  44. package/dist/generated/types/pub/techne/draft/registry/listTypeRequests.js +7 -0
  45. package/dist/generated/types/pub/techne/draft/registry/listTypes.d.ts +34 -0
  46. package/dist/generated/types/pub/techne/draft/registry/listTypes.js +7 -0
  47. package/dist/generated/types/pub/techne/draft/registry/publishType.d.ts +77 -0
  48. package/dist/generated/types/pub/techne/draft/registry/publishType.js +83 -0
  49. package/dist/generated/types/pub/techne/draft/registry/purgeType.d.ts +39 -0
  50. package/dist/generated/types/pub/techne/draft/registry/purgeType.js +34 -0
  51. package/dist/generated/types/pub/techne/draft/registry/requestType.d.ts +53 -0
  52. package/dist/generated/types/pub/techne/draft/registry/requestType.js +76 -0
  53. package/dist/generated/types/pub/techne/draft/registry/typeRequest.d.ts +22 -0
  54. package/dist/generated/types/pub/techne/draft/registry/typeRequest.js +12 -0
  55. package/dist/generated/types/pub/techne/draft/sync/indexRecord.d.ts +1 -1
  56. package/dist/generated/types/pub/techne/draft/verdict.d.ts +2 -2
  57. package/dist/platform.d.ts +14 -0
  58. package/dist/platform.js +16 -0
  59. package/dist/put/index.js +17 -7
  60. package/dist/query/index.d.ts +1 -10
  61. package/dist/query/index.js +1 -1
  62. package/dist/types-cli/emit.d.ts +20 -0
  63. package/dist/types-cli/emit.js +217 -0
  64. package/dist/types-cli/main.d.ts +5 -0
  65. package/dist/types-cli/main.js +63 -0
  66. package/dist/types-cli/resolve.d.ts +26 -0
  67. package/dist/types-cli/resolve.js +99 -0
  68. package/dist/wasm/index.d.ts +20 -3
  69. package/dist/wasm/index.js +6 -1
  70. package/dist/wasm/techne-wasm.gen.js +1 -1
  71. package/dist/wasm/techne-wasm2js.gen.js +26425 -25985
  72. package/package.json +23 -6
package/CHANGELOG.md ADDED
@@ -0,0 +1,139 @@
1
+ # Changelog
2
+
3
+ `techne-sdk` on npm and the `techne-sdk` crate share a version. Each entry names what changes for an app or
4
+ a crate user.
5
+
6
+ ## 0.3.0
7
+
8
+ Built on lexicons `agent/devplatform` b10ae5d and the platform's published API at regenOS `e3814f0f6`
9
+ (`inputs.pin.json`). Before publishing, the lexicons pin moves to the release tag (RELEASING.md: a tag,
10
+ never a branch).
11
+
12
+ ### Added: community and requested types
13
+
14
+ - **Registry methods** on the generated client: `pub.techne.draft.registry.publishType`, `getType`,
15
+ `listTypes`, `requestType`, `getTypeRequest`, `listTypeRequests`, `purgeType` and `blockIndex`, with
16
+ their record `pub.techne.draft.registry.typeRequest` and views in `registry.defs`.
17
+ - **`npx techne-sdk types <nsid>`** (the package's new `bin`): prints TypeScript types for any record
18
+ NSID. It asks the platform's `registry.getType` first and falls back to atproto lexicon resolution
19
+ (the authority's `_lexicon` TXT record names a DID, whose PDS holds the schema).
20
+ - **`scopes({ types })`** in `techne-sdk/auth`: an app names the types it writes (its own public types, a
21
+ community draft `pub.techne.draft.c.*`, an approved requested type), and each adds
22
+ `repo:<nsid>?action=create&action=update&action=delete`, the same scope the platform's own
23
+ least-privilege list asks for. `signIn` and `clientMetadata` take `types` too; pass the same list to
24
+ both, since the PDS refuses a request beyond what the metadata declares. A name that is not an NSID
25
+ throws a `TypeError`.
26
+ - **`appKey(clientId)` and `appSpace(did, clientId)`** in `techne-sdk/auth`: the key of the app's own
27
+ private space (the platform's `sidecar_rkey(client_id)`: base32, lowercase, no padding, of the client
28
+ id's SHA-256) and its address, `at://{did}/pub.techne.draft.space.private/{appKey}`. Write there with
29
+ `put(techne, [{ record, space }])` and read with `permissioned.listRecords({ space })`.
30
+ - **`scopes({ everything })`**: the opt-in to everything the person can reach. `'read'` adds the
31
+ `authRead` set; `'write'` adds `authRead`, `authWrite` and the `repo:` scope for the public
32
+ `community.lexicon.*` records (what the default was in 0.2.0).
33
+ - **Deletes are hinted.** `put(techne, records, { deletes })` now hints `sync.indexRecord` for each
34
+ public delete the PDS carried out, so the platform drops the record from its index without waiting for
35
+ the relay (which never brings it for a type that is not yet approved). A failed hint is ignored.
36
+ Deletes alone are `put(techne, [], { deletes })`.
37
+ - **The app's private space type** `pub.techne.draft.space.private` (one per app per person, keyed by
38
+ `appKey`) and the `pub.techne.draft.authPermissioned` permission set (the `permissioned.*` calls;
39
+ which spaces they reach is set by the `space:` scopes the app also asks for). `NSID.AUTH_PERMISSIONED`,
40
+ `NSID.SPACE_PRIVATE`.
41
+ - **`pub.techne.draft.query.composeRecords`**: up to 12 reads (`listRecords` or `getRecords` steps) in
42
+ one call, a later step binding to an earlier one's records.
43
+ - **Query `has`** (`pub.techne.draft.query#has`): a condition that some readable record names this one
44
+ through a role.
45
+ - `query.listRejections` reasons can say `budget`: a runtime type's record skipped because its author,
46
+ or the type, used up the day's indexing budget.
47
+
48
+ ### Changed
49
+
50
+ - `validate` (`techne-sdk/wasm`) knows the lexicons built into this version only. A community or
51
+ requested type answers `valid: false`, "no record lexicon"; the platform checks such records against
52
+ their lexicon when they are written. There is no `validateWith` in this release.
53
+ - `permissioned.getRecord` takes the 0016 space record address
54
+ (`at://{spaceAuthority}/space/{spaceType}/{skey}/{did}/{collection}/{rkey}`) as well as the 3-part one.
55
+
56
+ ### Changed (breaking)
57
+
58
+ - **The default sign-in scopes are narrowed to least privilege.** `scopes({ clientId })` (and so
59
+ `signIn` and `clientMetadata` without `scope`) asks for `atproto`,
60
+ `include:pub.techne.draft.authPermissioned?aud=<platform>%23atproto_appview`,
61
+ `space:pub.techne.draft.space.private?skey=<appKey>`, one
62
+ `rpc:<nsid>?aud=<platform>%23atproto_appview` for each signed-in read the SDK makes
63
+ (`query.listRecords`, `query.countRecords`, `query.getRecords`: `techne-sdk/query` and `put`'s
64
+ `curation`; `registry.getType`, `registry.listTypes`), which the platform narrows by the token's space
65
+ scopes to public data and the app's own space, and the `types` repo scopes (with
66
+ `rpc:pub.techne.draft.sync.indexRecord`, for `put`'s hint, when there are types), no longer `authRead`,
67
+ `authWrite` and the `community.lexicon.*` repo scope. `query.composeRecords` (which the SDK does not
68
+ call) still needs `everything: 'read'`. `scopes()` now needs `clientId` (it keys the
69
+ space; `TypeError` without it). An app that read or wrote beyond its own space and types passes
70
+ `everything: 'read'` or `'write'` (`everything: 'write'` is a superset of 0.2.0's default); its people re-consent
71
+ either way, since the scope changes. Without `everything: 'write'`, an app writing our public types
72
+ (a profile, an event) names them in `types`.
73
+
74
+ ### Removed (breaking)
75
+
76
+ - **`authPrivate` and the `appSpace.*` methods are gone** (they were in no published release):
77
+ `pub.techne.draft.appSpace.putRecord`, `getRecord`, `listRecords`, `deleteRecord`,
78
+ `NSID.AUTH_PRIVATE` and the `NSID.APP_SPACE_*` constants. The app's private space is an ordinary space
79
+ now: name `appSpace(did, clientId)` as the `space` of the `permissioned.*` calls (`put` does).
80
+ - **Query `include`.** `pub.techne.draft.query` no longer has `include`, and `listRecords` answers no
81
+ `included`; the platform refuses a query that names it. `Query.include` and `QueryRecord.included` are
82
+ gone from `techne-sdk/query`, and `NSID.QUERY_INCLUDE` from the NSID table. Read the related records with
83
+ `composeRecords` (one call), or a second `getRecords`.
84
+ - The old `coop.lexicon.draft.commons.*` names of methods the platform no longer serves
85
+ (`adjudicatePair`, `endorseRule`, `grantOperator`, `revokeOperator`, `revokeRule`, `restoreRecord`,
86
+ `takedownRecord`, `retireIdentity`, `unretireIdentity`) left the rename table.
87
+
88
+ The crate `techne-sdk` moves to 0.3.0 with the package (they share a version); its API is unchanged, it
89
+ builds on `techne-lexicon-check` 0.3.1.
90
+
91
+ ## 0.2.0
92
+
93
+ ### Changed: the verifier trusts operator-issued credentials (option (b))
94
+
95
+ `verify` (Rust `techne_sdk::verify`, `techne-sdk/wasm` in TypeScript) now trusts what the platform trusts
96
+ (regenOS `ee38bb7d7`, `provenancePolicy#vouchedWriter` at lexicons `v0.1.22-techne.45`):
97
+
98
+ - **Operator-issued credentials.** A credential counts when its issuer is the commons root, or an operator
99
+ named by one of the root's intact `pub.techne.draft.operator` records for a period that holds at the
100
+ credential's first-seen time (`validFrom` inclusive, `validUntil` exclusive, an absent `validUntil` is
101
+ open). With no first-seen time, only an open period holds. 0.1.0 trusted root-issued credentials only.
102
+ - **Root same-rkey revocation.** A credential is revoked by a record at its own revocation address, as
103
+ before, or at the same rkey in the root's repo.
104
+ - Both apply to `decide`'s `vouchedWriter` verdicts and to `chainVerified`.
105
+
106
+ **Breaking (Rust):** `verify::Record` gains `pub first_seen: Option<String>` (`firstSeen` in JSON,
107
+ absent by default). Code that builds a `Record` with a struct literal no longer compiles until it adds the
108
+ field, e.g. `first_seen: None`. That is why this release is 0.2.0: a `techne-sdk = "0.1"` requirement does
109
+ not pick it up; move to `"0.2"` and add the field. JSON input without `firstSeen` still parses. In TypeScript `ReadRecord` gains an
110
+ optional `firstSeen`, so nothing breaks there.
111
+
112
+ ### Added: `techne-sdk/auth`
113
+
114
+ Browser OAuth sign-in ("Sign in with Techne"): `signIn`, `signUp`, `restore`, `signOut`,
115
+ `onSessionDeleted`, `clientMetadata`, `scopes`, `includeScope`, `resolveClientId`,
116
+ `setOAuthClientFactory`, `redirectState` (the `state` a sign-in sent, after its redirect), and the
117
+ constants `TECHNE_PLATFORM_DID`, `TECHNE_TOWN`, `TECHNE_TOWN_PDS`. `clientMetadata` answers
118
+ `@atproto/oauth-types`' `OAuthClientMetadataInput`. The React half (`techne-sdk/auth/react`:
119
+ `TechneProvider`, `SignInWithTechne`) is not included yet.
120
+
121
+ New dependencies for every install, whether or not an app imports `techne-sdk/auth`:
122
+ `@atproto/oauth-client-browser` (loaded only on first use, so it stays out of bundles that do not sign
123
+ in) and `@atproto/oauth-types`. Some of what they pull in declares Node >= 22, as this repo already
124
+ requires; npm warns (or fails under `engine-strict`) on older Node.
125
+
126
+ ### Changed: inputs
127
+
128
+ - Lexicons pinned at `v0.1.22-techne.45` (check `techne-lexicon-check` 0.3.0) and the platform's published
129
+ API at regenOS `ee38bb7d7`. Types and clients are regenerated from them.
130
+
131
+ ### Docs
132
+
133
+ - The techne.town defaults go live at the Techne release. Until then, pass `pds` (and `plcUrl`,
134
+ `handleDomain`, `platform`) explicitly; ask the Techne team for the current staging values. Neither the
135
+ package nor the crate names a staging host.
136
+
137
+ ## 0.1.0
138
+
139
+ First release, on npm and crates.io.
package/README.md CHANGED
@@ -25,11 +25,12 @@ Every import goes through the package's `exports`, so the resolver has to read t
25
25
  | `techne-sdk/types/<nsid path>` | one lexicon's types, e.g. `techne-sdk/types/social/scenius/getContactInvite` |
26
26
  | `techne-sdk/react` | `useEvent(uri)`: one commons event or place as its versions, with the check's verdict |
27
27
  | `techne-sdk/versions` | the same state without React: `eventState`, `verifyAnswer`, version labels |
28
+ | `techne-sdk/auth` | sign-in ("Sign in with Techne"): `signIn`, `signUp`, `restore`, `signOut`, `clientMetadata`, `scopes`, `appKey`, `appSpace` (browser OAuth) |
28
29
  | `techne-sdk/connect` | `connect(session, platform)` / `connectHosted(did, fetchHandler)`: the clients over one session |
29
- | `techne-sdk/put` | `put(techne, records, { deletes })`: the one write, deletes included |
30
+ | `techne-sdk/put` | `put(techne, records, { deletes })`: the one write, deletes included (public deletes hinted to the platform); `put(techne, [], { deletes })` for deletes alone |
30
31
  | `techne-sdk/query` | the platform's generic queries: `listRecords`, `getRecords`, hosts |
31
32
  | `techne-sdk/links` | link tokens: create, redeem, check, revoke |
32
- | `techne-sdk/wasm` | the check itself: `validate`, `decide`, `verify` |
33
+ | `techne-sdk/wasm` | the check itself: `validate`, `decide`, `verify` (`validate` knows the built-in lexicons only; a runtime type is checked by the platform on write) |
33
34
  | `techne-sdk/catalog` | the browsable lexicon catalog |
34
35
  | `techne-sdk/nsid`, `techne-sdk/nsid.json` | every NSID as a constant (`NSID`, `METHOD`) |
35
36
 
@@ -54,11 +55,56 @@ function Event({ uri }: { uri: string }) {
54
55
 
55
56
  Pass `{ claims }` too, and `verification` holds the check's answer for every record (valid, signer, chain verified).
56
57
 
58
+ ## Types for any type
59
+
60
+ The generated client covers the platform's own lexicons. For a community draft, a requested type or any other
61
+ published NSID, print its types:
62
+
63
+ ```sh
64
+ npx techne-sdk types pub.techne.draft.c.<id>.toolListing > src/toolListing.ts
65
+ ```
66
+
67
+ It asks the platform's registry (`registry.getType`) first, then atproto lexicon resolution (the NSID's
68
+ `_lexicon` TXT record, then the schema record on that DID's PDS). `--platform <url>` (or `TECHNE_PLATFORM_URL`)
69
+ picks the platform; `--out <file>` writes the file. A ref to another document comes out as `unknown`, with the
70
+ ref in a comment.
71
+
72
+ ## Sign in with Techne
73
+
74
+ `techne-sdk/auth` signs a person in from the browser. Each app is its own atproto OAuth client, the way "Sign in with Google" works: the app serves its client metadata at its client id, the person signs in at their own PDS, and the app keeps the session (an `OAuthSession`, with `did` and `fetchHandler`) that `connect` takes. It runs on `@atproto/oauth-client-browser`, loaded the first time it is used.
75
+
76
+ ```ts
77
+ import { clientMetadata, restore, signIn, TECHNE_PLATFORM_DID } from 'techne-sdk/auth'
78
+ import { connect } from 'techne-sdk/connect'
79
+
80
+ const clientId = 'https://cafes.example/oauth-client-metadata.json'
81
+
82
+ // Serve this JSON at clientId (a static file or a route).
83
+ const metadata = clientMetadata({ clientId, clientName: 'Cafe finder' })
84
+
85
+ // On every page load: finishes a sign-in when the page is the redirect back, else restores a kept session.
86
+ const session = await restore({ clientId })
87
+ if (!session) await signIn({ clientId, handle: 'alice' }) // alice.techne.town, once techne.town is live (see below)
88
+ else {
89
+ const techne = connect(session, TECHNE_PLATFORM_DID)
90
+ }
91
+ ```
92
+
93
+ - **Who:** with no `handle`, the sign-in starts at the default PDS (techne.town), which asks who you are. A bare name (`alice`) is a handle on the default handle domain. A full handle, a DID or a PDS URL from any PDS is used as given. `signUp({ clientId })` opens the PDS's create-account screen.
94
+ - **Scopes:** `scopes({ clientId })` is what it asks for by default, least privilege: `atproto`; the platform's `authPermissioned` permission set with the platform as its audience (the `permissioned.*` calls: private writes, reads and deletes); the app's own private space, `space:pub.techne.draft.space.private?skey=<appKey>`; and an `rpc:<nsid>?aud=<platform>%23atproto_appview` scope for each generic read the SDK makes signed in: `query.listRecords`, `query.countRecords` and `query.getRecords` (`techne-sdk/query`, `put`'s curation answer) and `registry.getType` and `registry.listTypes`. The platform narrows those reads by the token's space scopes, so they reach public data and the app's own space. An app passes the types it writes as `types: [nsid, ...]`, and each adds a `repo:<nsid>` scope (create, update, delete), as the platform's own least-privilege list does, plus `rpc:pub.techne.draft.sync.indexRecord` so `put` can hint the platform what it wrote (a pending type's records are indexed no other way); without `types` the app writes no public record. `query.composeRecords` is not in the default (the SDK makes no such call); an app that calls it asks for `everything: 'read'`. Everything the person can reach (their personal space, their circles, beacons shared with them) is an opt-in: `everything: 'read'` adds the `authRead` set, `everything: 'write'` adds `authRead`, `authWrite` and a `repo:` scope for the public `community.lexicon.*` records (then our own public types need no `types` entry). The consent page shows those with a large warning; ask only if the app needs them. Pass the same `types` and `everything` to `signIn` and `clientMetadata`, since the PDS refuses a request beyond what the metadata declares. Pass `scope` to ask for other scopes, and pass it to both.
95
+ - **The app's private space:** `appSpace(session.did, clientId)` is `at://{did}/pub.techne.draft.space.private/{appKey}`, where `appKey(clientId)` is the client id hashed (base32, lowercase, no padding, of its SHA-256; the platform's `sidecar_rkey`). Write there with `put(techne, [{ record, space: appSpace(did, clientId) }])` and read with `permissioned.listRecords({ space })`. Only that person reads it, and only through this app. In development the client id is the loopback client's, `resolveClientId(options)` with the same options `signIn` took: it carries the scope, so it changes with the port, `types` and `everything`, and so does the space. Its scope names the space type without a key (an id cannot carry its own hash), so the consent page shows the private-data warning; the platform still serves the space only for the app its key names.
96
+ - **Development:** on `localhost` or `127.0.0.1` you can leave `clientId` out. The SDK then uses atproto's loopback client, so you don't need to host anything.
97
+ - **Sessions:** the library refreshes tokens itself. `restore` returns the session, `null` when nobody is signed in, and rejects when a sign-in or refresh failed. `signOut({ clientId, session })` revokes the session. `onSessionDeleted` tells you when the library drops a session. A `state` passed to `signIn` comes back from `redirectState({ clientId })` on the page the redirect lands on.
98
+ - **Another deployment:** `platform` names the platform's DID (`TECHNE_PLATFORM_DID` by default). `pds`, `plcUrl` and `handleDomain` name the PDS people sign in at, its PLC directory and its handle domain. Pass them the same way to every call.
99
+
100
+ **Before the Techne release:** the techne.town defaults (`TECHNE_PLATFORM_DID`, the techne.town PDS and handle domain) go live at the Techne release. Until then, `signIn()` without `pds` fails: pass `pds`, `plcUrl`, `handleDomain` and `platform` explicitly, and ask the Techne team for the current staging values.
101
+
57
102
  ## Layout
58
103
 
59
104
  | Path | What |
60
105
  |---|---|
61
106
  | `src/` | the TypeScript package. `src/generated/`, `src/catalog/catalog.gen.ts` and `src/wasm/*.gen.*` are generated and committed |
107
+ | `src/types-cli/` | the `techne-sdk types <nsid>` bin: resolve (`resolve.ts`), emit (`emit.ts`), golden files in `testdata/` (`UPDATE_GOLDEN=1 npm run test:types-cli`) |
62
108
  | `crates/techne-sdk/` | the Rust crate, with the shared fixtures (`fixtures/cases.json`) both languages must answer identically |
63
109
  | `inputs/` | the codegen inputs, copied by `scripts/inputs-sync.mjs` and pinned in `inputs.pin.json`: `inputs/lexicons/` (the lexicons repo at `lexicons.tag`) and `inputs/platform-api/` (the platform's routed method lexicons, the atproto methods it serves and its NSID rename map, at `platformApi.rev`) |
64
110
  | `lexicons-base/` | standard atproto repo-op lexicons the generated client needs |
@@ -0,0 +1,8 @@
1
+ /** SHA-256 (FIPS 180-4) of `bytes`. */
2
+ export declare function sha256(bytes: Uint8Array): Uint8Array;
3
+ /** The key of the app `clientId`'s private space: the platform's `sidecar_rkey(client_id)`. */
4
+ export declare function appKey(clientId: string): string;
5
+ /** The address of `did`'s private space for the app `clientId`: `at://{did}/pub.techne.draft.space.private/{appKey}`,
6
+ * the `space` a `put` or `permissioned.listRecords` names. In development (the loopback client) pass the
7
+ * loopback client id, `resolveClientId(options)`. */
8
+ export declare function appSpace(did: string, clientId: string): string;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * An app's own private space (`pub.techne.draft.space.private`): its key and address. The key is the
3
+ * platform's `sidecar_rkey(client_id)` (regenOS crates/regenos-lexicons/src/sidecar.rs): RFC 4648 base32,
4
+ * lowercase, no padding, of the SHA-256 of the client id's UTF-8 bytes. Synchronous (no WebCrypto), so
5
+ * `scopes()` and `clientMetadata()` stay synchronous.
6
+ */
7
+ import { NSID } from '../generated/nsid.js';
8
+ const K = new Uint32Array([
9
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
10
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
11
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
12
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
13
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
14
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
15
+ ]);
16
+ /** SHA-256 (FIPS 180-4) of `bytes`. */
17
+ export function sha256(bytes) {
18
+ const bitLen = bytes.length * 8;
19
+ const padded = new Uint8Array(Math.ceil((bytes.length + 9) / 64) * 64);
20
+ padded.set(bytes);
21
+ padded[bytes.length] = 0x80;
22
+ const view = new DataView(padded.buffer);
23
+ view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
24
+ view.setUint32(padded.length - 4, bitLen >>> 0);
25
+ const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
26
+ const w = new Uint32Array(64);
27
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
28
+ for (let off = 0; off < padded.length; off += 64) {
29
+ for (let i = 0; i < 16; i++)
30
+ w[i] = view.getUint32(off + i * 4);
31
+ for (let i = 16; i < 64; i++) {
32
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
33
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
34
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
35
+ }
36
+ let [a, b, c, d, e, f, g, hh] = h;
37
+ for (let i = 0; i < 64; i++) {
38
+ const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
39
+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
40
+ hh = g;
41
+ g = f;
42
+ f = e;
43
+ e = (d + t1) >>> 0;
44
+ d = c;
45
+ c = b;
46
+ b = a;
47
+ a = (t1 + t2) >>> 0;
48
+ }
49
+ h[0] += a;
50
+ h[1] += b;
51
+ h[2] += c;
52
+ h[3] += d;
53
+ h[4] += e;
54
+ h[5] += f;
55
+ h[6] += g;
56
+ h[7] += hh;
57
+ }
58
+ const out = new Uint8Array(32);
59
+ const outView = new DataView(out.buffer);
60
+ for (let i = 0; i < 8; i++)
61
+ outView.setUint32(i * 4, h[i]);
62
+ return out;
63
+ }
64
+ /** RFC 4648 base32, lowercase, no padding (regenOS `base32_lower_nopad`). */
65
+ function base32LowerNoPad(bytes) {
66
+ const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';
67
+ let out = '';
68
+ let buffer = 0;
69
+ let bits = 0;
70
+ for (const byte of bytes) {
71
+ buffer = ((buffer << 8) | byte) & 0xffff;
72
+ bits += 8;
73
+ while (bits >= 5) {
74
+ bits -= 5;
75
+ out += alphabet[(buffer >> bits) & 31];
76
+ }
77
+ }
78
+ if (bits > 0)
79
+ out += alphabet[(buffer << (5 - bits)) & 31];
80
+ return out;
81
+ }
82
+ /** The key of the app `clientId`'s private space: the platform's `sidecar_rkey(client_id)`. */
83
+ export function appKey(clientId) {
84
+ if (!clientId)
85
+ throw new TypeError('techne-sdk/auth: appKey needs the client id');
86
+ return base32LowerNoPad(sha256(new TextEncoder().encode(clientId)));
87
+ }
88
+ /** The address of `did`'s private space for the app `clientId`: `at://{did}/pub.techne.draft.space.private/{appKey}`,
89
+ * the `space` a `put` or `permissioned.listRecords` names. In development (the loopback client) pass the
90
+ * loopback client id, `resolveClientId(options)`. */
91
+ export function appSpace(did, clientId) {
92
+ if (!did.startsWith('did:'))
93
+ throw new TypeError(`techne-sdk/auth: appSpace takes a DID (got ${JSON.stringify(did)})`);
94
+ return `at://${did}/${NSID.SPACE_PRIVATE}/${appKey(clientId)}`;
95
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * techne-sdk/auth — sign-in for an app on Techne ("Sign in with Techne"). Each app is its own atproto OAuth client, the
3
+ * "Sign in with Google" shape: it serves its own client metadata ({@link clientMetadata}) at its client id,
4
+ * the person signs in at their own PDS, and the app holds the session (an OAuthSession: `did` and
5
+ * `fetchHandler`) that `connect` takes. Browser only, over `@atproto/oauth-client-browser`.
6
+ *
7
+ * ```ts
8
+ * const clientId = 'https://cafes.example/oauth-client-metadata.json'
9
+ * const session = await restore({ clientId }) // after the redirect back, or a later visit
10
+ * if (!session) await signIn({ clientId, handle: 'alice' }) // redirects; alice.techne.town
11
+ * const techne = connect(session, TECHNE_PLATFORM_DID)
12
+ * ```
13
+ *
14
+ * What it asks for ({@link scopes}), least privilege by default: `atproto`; the platform's
15
+ * `authPermissioned` permission set with the platform's appview as its audience
16
+ * (`include:pub.techne.draft.authPermissioned?aud=<platform>%23atproto_appview`: the `permissioned.*` calls);
17
+ * the app's own private space, `space:pub.techne.draft.space.private?skey=<appKey>` ({@link appKey}: the
18
+ * client id hashed, so the scope names this app's space and no other); `rpc:<nsid>?aud=<platform>%23atproto_appview`
19
+ * for each generic read the SDK makes signed in (`query.listRecords`, `countRecords` and
20
+ * `getRecords`, behind `techne-sdk/query` and `put`'s curation read, and `registry.getType` and `listTypes`),
21
+ * which the platform narrows by the token's space scopes to public data and the app's own space; and one `repo:<nsid>` scope
22
+ * (create, update, delete) per type the app writes, named with the `types` option, sorted, as the platform's
23
+ * own least-privilege list does (a scope names whole NSIDs only, and no published permission set can name a
24
+ * type minted after it), with `rpc:pub.techne.draft.sync.indexRecord` at the platform so `put` can hint
25
+ * what it wrote.
26
+ * Everything the person can reach (their personal space, their circles, beacons
27
+ * shared with them) is an opt-in, `everything: 'read'` (the `authRead` set) or `everything: 'write'`
28
+ * (`authRead` and `authWrite`, plus a `repo:` scope for our public homes outside our namespace,
29
+ * `community.lexicon.*`, from the placement manifest, `placement.gen.ts`); the consent page shows those
30
+ * with a large warning. Pass the same options to {@link clientMetadata} and {@link signIn}: the PDS refuses
31
+ * a request beyond what the metadata declares. The platform is {@link TECHNE_PLATFORM_DID} unless a
32
+ * `platform` option names another (a test deployment's did:plc).
33
+ *
34
+ * Where it starts: no handle starts at the techne.town PDS ({@link TECHNE_TOWN_PDS}), which asks who you
35
+ * are; a bare name (`alice`) is a techne.town handle (`alice.techne.town`); a full handle, a DID or a PDS
36
+ * URL from any PDS goes as given. `signUp` goes to the techne.town PDS with `prompt: 'create'`, its
37
+ * create-account screen. An app whose people live on another PDS (a test deployment's) names it with the `pds`
38
+ * option, and its PLC directory with `plcUrl`: handles then resolve at that PDS, a sign-in with no
39
+ * handle and every sign-up start there, a bare name takes `handleDomain`, and DIDs resolve at that PLC.
40
+ *
41
+ * On localhost (or 127.0.0.1) the client is atproto's loopback client
42
+ * (`http://localhost?redirect_uri=http://127.0.0.1:<port>/&scope=…`), with or without a client id, so an app
43
+ * runs in development with nothing hosted. A page elsewhere with no client id cannot sign in. The loopback
44
+ * id carries its scope, so its private-space scope names no key (and the consent page shows the
45
+ * private-data warning); its {@link appSpace} is keyed by the whole id ({@link resolveClientId} with the
46
+ * same options as {@link signIn}), which changes with the port and the scope.
47
+ *
48
+ * Restore and refresh. {@link restore} is the library's `init()`: it finishes a sign-in when the page is
49
+ * the redirect back, else restores the session kept in IndexedDB. It does not force a refresh: the
50
+ * library refreshes the tokens when they are about to expire, and again on every request whose token has
51
+ * expired (the session's `fetchHandler` does it), so a restored session is used as it is. It answers the
52
+ * session, `null` when nobody is signed in, and rejects when the sign-in failed (the person said no) or the
53
+ * kept session could not be refreshed (the library has then deleted it); what signed out looks like is the
54
+ * caller's (the React provider shows the anonymous client). One `init()` runs per client however many ask
55
+ * (the redirect's code can be used once), until {@link signOut}. A session the library deletes later (its
56
+ * refresh token revoked) is announced to {@link onSessionDeleted} listeners. The `state` a {@link signIn}
57
+ * sent comes back from {@link redirectState} on the page the redirect lands on (the same `init()`).
58
+ *
59
+ * One BrowserOAuthClient per client id, made on first use. Tests (and other runtimes) inject their own
60
+ * with {@link setOAuthClientFactory}.
61
+ */
62
+ import type { AuthorizeOptions, OAuthSession } from '@atproto/oauth-client-browser';
63
+ import { type OAuthClientMetadataInput } from '@atproto/oauth-types';
64
+ import { TECHNE_PLATFORM_DID } from '../platform.js';
65
+ export { appKey, appSpace } from './app-key.js';
66
+ export { TECHNE_PLATFORM_DID };
67
+ export type { OAuthSession };
68
+ /** The techne.town handle domain: a bare name signs in as `<name>.techne.town`. */
69
+ export declare const TECHNE_TOWN = "techne.town";
70
+ /** The techne.town PDS: where a sign-in with no handle, and every sign-up, starts. */
71
+ export declare const TECHNE_TOWN_PDS = "https://pds.techne.town";
72
+ /** The OAuth client the module drives: what it uses of BrowserOAuthClient. */
73
+ export interface OAuthClientLike {
74
+ init(refresh?: boolean): Promise<{
75
+ session: OAuthSession;
76
+ state?: string | null;
77
+ } | undefined>;
78
+ signInRedirect(input: string, options?: AuthorizeOptions): Promise<unknown>;
79
+ revoke(sub: string): Promise<void>;
80
+ }
81
+ /** What a factory is given to make a client. */
82
+ export interface ClientConfig {
83
+ /** The client id: the app's https metadata URL, or a loopback id. */
84
+ clientId: string;
85
+ /** Where handles are resolved: the home PDS (`pds`, techne.town by default), which answers `resolveHandle`. */
86
+ handleResolver: string;
87
+ /** The PLC directory a did:plc resolves at; the library's (plc.directory) when absent. */
88
+ plcDirectoryUrl?: string;
89
+ /** Call when the library deletes a session (a failed refresh, a revocation). */
90
+ onSessionDeleted: (sub: string, cause: unknown) => void;
91
+ }
92
+ export type OAuthClientFactory = (config: ClientConfig) => OAuthClientLike | Promise<OAuthClientLike>;
93
+ /** Make every client with `make` instead of BrowserOAuthClient (tests, other runtimes); `undefined` goes
94
+ * back to the default. Forgets every client made so far. */
95
+ export declare function setOAuthClientFactory(make: OAuthClientFactory | undefined): void;
96
+ /** What every call takes to name its client. */
97
+ export interface ClientOptions {
98
+ /** The app's client id: the https URL of the metadata it serves (conventionally ending
99
+ * `/oauth-client-metadata.json`). Omitted, or on a loopback page, the loopback client. */
100
+ clientId?: string;
101
+ /** The platform's service DID: the audience of the scopes. {@link TECHNE_PLATFORM_DID} by default. */
102
+ platform?: string;
103
+ /** The scopes to ask for; {@link scopes} by default. */
104
+ scope?: string | readonly string[];
105
+ /** The types the app writes, for the default {@link scopes} (ignored with `scope`). */
106
+ types?: readonly string[];
107
+ /** Ask for everything the person can reach, for the default {@link scopes} (ignored with `scope`). */
108
+ everything?: Everything;
109
+ /** The page's location; `globalThis.location` by default. */
110
+ location?: Pick<Location, 'protocol' | 'hostname' | 'port'>;
111
+ /** The home PDS: where handles resolve, and where a sign-in with no handle and every sign-up start.
112
+ * {@link TECHNE_TOWN_PDS} by default. Read when the client id's client is first made. */
113
+ pds?: string;
114
+ /** The PLC directory a did:plc resolves at (a test deployment may run its own); plc.directory by default. Read when
115
+ * the client id's client is first made. */
116
+ plcUrl?: string;
117
+ /** The handle domain a bare name signs in under; {@link TECHNE_TOWN} by default. */
118
+ handleDomain?: string;
119
+ }
120
+ /** The `include:` scope for the permission set `nsid` with `platform`'s appview as its audience:
121
+ * `include:<nsid>?aud=<platform>%23atproto_appview`. {@link TECHNE_PLATFORM_DID} by default; another
122
+ * platform (a local stack, a test deployment) passes its own DID. */
123
+ export declare function includeScope(nsid: string, platform?: string): string;
124
+ /** The opt-in to everything the person can reach: `'read'` adds the platform's `authRead` set, `'write'`
125
+ * `authRead` and `authWrite` (and the `repo:` scope for our public `community.lexicon.*` homes). */
126
+ export type Everything = 'read' | 'write';
127
+ /** What {@link scopes} takes. */
128
+ export interface ScopesOptions {
129
+ /** The app's client id: the key of its private space ({@link appKey}). */
130
+ clientId: string;
131
+ /** The platform's service DID; {@link TECHNE_PLATFORM_DID} by default. */
132
+ platform?: string;
133
+ /** The types the app writes: one `repo:<nsid>` scope each. */
134
+ types?: readonly string[];
135
+ /** Everything the person can reach, an opt-in (see {@link Everything}); none by default. */
136
+ everything?: Everything;
137
+ }
138
+ /** The scopes signIn asks for by default (see the module doc): least privilege, the permissioned calls,
139
+ * the app's own private space, an `rpc` scope per read in `READ_METHODS` and a `repo` scope per type
140
+ * in `types`; `everything` widens it. A name in
141
+ * `types` that is not an NSID throws a TypeError. */
142
+ export declare function scopes(o: ScopesOptions): string[];
143
+ /** What {@link clientMetadata} takes. */
144
+ export interface ClientMetadataOptions {
145
+ /** The https URL the document is served at. */
146
+ clientId: string;
147
+ /** Where the sign-in comes back to; `[<origin of clientId>/]` by default. */
148
+ redirectUris?: [string, ...string[]];
149
+ clientName?: string;
150
+ clientUri?: string;
151
+ logoUri?: string;
152
+ /** The scopes, as {@link ClientOptions.scope}. */
153
+ scope?: string | readonly string[];
154
+ /** The types the app writes, as {@link ClientOptions.types}. */
155
+ types?: readonly string[];
156
+ /** As {@link ClientOptions.everything}. */
157
+ everything?: Everything;
158
+ platform?: string;
159
+ }
160
+ /** The client-metadata document an app serves at its client id: a public browser client (no secret,
161
+ * DPoP-bound tokens), asking for {@link scopes} by default. */
162
+ export declare function clientMetadata(o: ClientMetadataOptions): OAuthClientMetadataInput;
163
+ /** The client id a call signs in as: the loopback client on a loopback page or with no client id, else
164
+ * `clientId`. Its {@link appSpace} is the app's private space. */
165
+ export declare function resolveClientId(o: ClientOptions): string;
166
+ /** Listen for the library deleting a session of this client (a refresh that failed, a revocation
167
+ * elsewhere). Answers the unsubscribe. */
168
+ export declare function onSessionDeleted(o: ClientOptions, listener: (sub: string, cause: unknown) => void): () => void;
169
+ /** What {@link signIn} takes. */
170
+ export interface SignInOptions extends ClientOptions {
171
+ /** Who: a bare name (under `handleDomain`), a full handle, a DID or a PDS URL. None starts at the home PDS.
172
+ * With `signUp` only an https PDS URL is used (the PDS to create the account at); any other handle is
173
+ * ignored and the sign-up starts at the home PDS, which asks for the new handle itself. */
174
+ handle?: string;
175
+ /** Create an account at the home PDS (`prompt: 'create'`). */
176
+ signUp?: boolean;
177
+ /** Handed back by the redirect: {@link redirectState} answers it there. */
178
+ state?: string;
179
+ }
180
+ /** Sign in: redirects to the person's PDS, and comes back to the app's redirect URI (then {@link restore}). */
181
+ export declare function signIn(o?: SignInOptions): Promise<void>;
182
+ /** {@link signIn} with `signUp: true`. */
183
+ export declare function signUp(o?: Omit<SignInOptions, 'signUp'>): Promise<void>;
184
+ /** The signed-in session, or `null` (see the module doc for the redirect, refresh and errors). */
185
+ export declare function restore(o?: ClientOptions): Promise<OAuthSession | null>;
186
+ /** The `state` the {@link signIn} that led here sent, on the page its redirect lands on; `null` when the
187
+ * page is not that redirect (a session restored from storage, or nobody signed in). */
188
+ export declare function redirectState(o?: ClientOptions): Promise<string | null>;
189
+ /** Sign out: revokes `session` at its PDS and forgets it here. */
190
+ export declare function signOut(o: ClientOptions & {
191
+ session: Pick<OAuthSession, 'did'>;
192
+ }): Promise<void>;