@metalabel/dfos-client 0.30.0 → 0.32.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.
- package/README.md +34 -4
- package/dist/api-auth.d.ts +243 -0
- package/dist/api-auth.js +336 -0
- package/dist/siwd.d.ts +41 -7
- package/dist/siwd.js +15 -2
- package/package.json +9 -5
package/README.md
CHANGED
|
@@ -6,8 +6,6 @@ If verification logic appears in this package, that is the bug: every proof come
|
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
|
-
> **Not yet published — pre-release.** This package is `private` until it ships with a stamped release; until then it is consumable only inside this workspace.
|
|
10
|
-
|
|
11
9
|
```bash
|
|
12
10
|
npm install @metalabel/dfos-client @metalabel/dfos-protocol @metalabel/dfos-web-relay
|
|
13
11
|
```
|
|
@@ -78,10 +76,42 @@ import { indexedDbStore, memoryStore } from '@metalabel/dfos-client/store';
|
|
|
78
76
|
### `@metalabel/dfos-client/siwd`
|
|
79
77
|
|
|
80
78
|
```typescript
|
|
81
|
-
import {
|
|
79
|
+
import {
|
|
80
|
+
createSiwdLoginRequest,
|
|
81
|
+
readSiwdCallback,
|
|
82
|
+
siwdSigningInput,
|
|
83
|
+
verifySiwd,
|
|
84
|
+
} from '@metalabel/dfos-client/siwd';
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Sign In With DFOS. The three verbs above are the relying-party login kit, in the order a login uses them: `createSiwdLoginRequest` mints the challenge and builds the `/authorize` URL to redirect to, `readSiwdCallback` parses what comes back, and `verifySiwd` verifies it — mint → redirect, read → verify. The `expect` object `createSiwdLoginRequest` returns (nonce, domain, and the DID when the challenge is bound to one) is what `verifySiwd` checks against, so the relying party MUST persist it across the redirect: a verifier that takes its expectation from the callback has implemented the check and none of the protection. See [`examples/siwd-demo`](../../examples/siwd-demo) for the reference consumer.
|
|
88
|
+
|
|
89
|
+
The `nonce`/`consumeNonce` pair on the expectation (supply exactly one) is the spec's [two replay disciplines](../../specs/SIWD.md#replay-prevention), one field each:
|
|
90
|
+
|
|
91
|
+
**`expect.nonce` — flow-bound login.** For a backend granting only a browser session (`scope=identity`), source the expected nonce from state you bound to that browser at mint time — a server-side session, or the nonce sealed under your own key in an `httpOnly` cookie — and compare:
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
// mint: cookie = `${nonce}.${hmacSha256(secret, nonce)}`, httpOnly, Max-Age ≤ your window
|
|
95
|
+
// verify: unseal the cookie back to `nonce` (full-length tag, constant-time compare), then
|
|
96
|
+
await verifySiwd(client, jws, { domain, nonce });
|
|
82
97
|
```
|
|
83
98
|
|
|
84
|
-
|
|
99
|
+
The seal (or the session) is what makes this a defense at all: a _bare_ cookie value is presenter-supplied, and an attacker replaying a captured JWS can read the nonce out of the artifact and send it as the cookie. Never compare against anything the presenter could have authored.
|
|
100
|
+
|
|
101
|
+
**`consumeNonce` — spend the nonce.** Required the moment success grants anything beyond a session with the presenting browser (a credential-returning scope, a portable token, a profile-B mailbox flow):
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
await verifySiwd(client, jws, {
|
|
105
|
+
domain,
|
|
106
|
+
consumeNonce: async (nonce) => (await store.getdel(nonce)) !== null,
|
|
107
|
+
});
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`consumeNonce` returns true iff **this** verifier minted the nonce and it was unspent — membership in verifier-minted state is what satisfies the spec's rule that the verifier MUST have minted the nonce it checks, and deleting it in the same operation is what makes it single-use. The atomicity is the caller's: a get-then-delete lets two concurrent replays both win, where a Redis `GETDEL` or a `DELETE … RETURNING` does not. Under either discipline the nonce check runs at most once, and only after every other check has passed, so an invalid presentation can never burn a nonce the user is still holding.
|
|
111
|
+
|
|
112
|
+
`createSiwdLoginRequest` throws rather than returning an error on the two things that are RP misconfiguration: an `authorizeUrl` or `redirectUri` that is not an absolute URL, and any scope other than `identity` over a loopback redirect (a local port holds no `client_did` for a credential to be issued to — see [SIWD.md](../../specs/SIWD.md)).
|
|
113
|
+
|
|
114
|
+
`siwdSigningInput(challenge)` is the pure byte contract both the signer and the verifier share (see [SIWD.md](../../specs/SIWD.md)); `createSiwdChallenge` mints a challenge on its own for a caller building its own redirect; `verifySiwd` is a no-throw verifier that accepts only a current `authKeys` entry of a non-deleted identity.
|
|
85
115
|
|
|
86
116
|
## License
|
|
87
117
|
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { a as Client } from './types-ByxTj1u-.js';
|
|
2
|
+
import '@metalabel/dfos-protocol/chain';
|
|
3
|
+
import '@metalabel/dfos-protocol/credentials';
|
|
4
|
+
import '@metalabel/dfos-web-relay/peer-client';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The normative JWS header `typ` for a request proof (API-AUTH.md). Signers MUST
|
|
8
|
+
* set it; `verifyApiRequest` rejects anything else — it is also what lets
|
|
9
|
+
* typ-routing dispatchers tell a proof apart from credentials and chain ops.
|
|
10
|
+
*/
|
|
11
|
+
declare const REQUEST_PROOF_JWS_TYP = "did:dfos:request-proof";
|
|
12
|
+
/**
|
|
13
|
+
* The digest of zero octets. A request with no body hashes the empty string —
|
|
14
|
+
* there is deliberately no absent-member form for bodyless requests, so every
|
|
15
|
+
* proof is checked the same way.
|
|
16
|
+
*/
|
|
17
|
+
declare const EMPTY_BODY_SHA256 = "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU";
|
|
18
|
+
/** Size cap on the serialized proof token, checked BEFORE any decode. */
|
|
19
|
+
declare const MAX_REQUEST_PROOF_SIZE = 4096;
|
|
20
|
+
/** RECOMMENDED acceptance window `W` — how old a proof may be, in seconds. */
|
|
21
|
+
declare const DEFAULT_PROOF_WINDOW_SECONDS = 60;
|
|
22
|
+
/** RECOMMENDED clock-skew allowance `S` — how forward-dated a proof may be. */
|
|
23
|
+
declare const DEFAULT_PROOF_SKEW_SECONDS = 60;
|
|
24
|
+
/**
|
|
25
|
+
* The binding cap on `W + S`: the total span over which any one proof is
|
|
26
|
+
* accepted, and therefore its worst-case replay window. A configuration
|
|
27
|
+
* exceeding it is refused rather than clamped — a deployment that silently got a
|
|
28
|
+
* 10-minute replay window it did not ask for is the failure this forbids.
|
|
29
|
+
*/
|
|
30
|
+
declare const MAX_PROOF_FRESHNESS_SPAN_SECONDS = 300;
|
|
31
|
+
/** The v0 action registry's only token. */
|
|
32
|
+
declare const DEFAULT_API_ACTION = "read:profile";
|
|
33
|
+
/**
|
|
34
|
+
* Default cap on the decoded body a verifier will hash, in bytes (1 MiB). The v0
|
|
35
|
+
* action registry is bodyless, so this never binds today; it is the defensive
|
|
36
|
+
* ceiling for the first body-bearing action, overridable per verifier.
|
|
37
|
+
*/
|
|
38
|
+
declare const MAX_BODY_BYTES = 1048576;
|
|
39
|
+
interface RequestProofPayload {
|
|
40
|
+
/** The HTTP method, uppercase. */
|
|
41
|
+
method: string;
|
|
42
|
+
/** The API's lowercase authority — `host` on 443, `host:port` otherwise. */
|
|
43
|
+
host: string;
|
|
44
|
+
/** The exact origin-form request target — path plus query string, byte for byte. */
|
|
45
|
+
path: string;
|
|
46
|
+
/** Canonical unpadded base64url of the SHA-256 of the raw request body octets. */
|
|
47
|
+
bodyHash: string;
|
|
48
|
+
/** CID of the leaf credential presented alongside this proof. */
|
|
49
|
+
credentialCID: string;
|
|
50
|
+
/** Issued-at — unix seconds (positive integer). */
|
|
51
|
+
iat: number;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* THE BYTE CONTRACT. Serializes a payload to the canonical bytes that ARE the
|
|
55
|
+
* JWS payload segment — a fixed key order (method, host, path, bodyHash,
|
|
56
|
+
* credentialCID, iat) with no insignificant whitespace, and `iat` as a bare JSON
|
|
57
|
+
* integer.
|
|
58
|
+
*
|
|
59
|
+
* HTML ESCAPING IS OFF, by construction: `path` routinely carries `&` and admits
|
|
60
|
+
* `<` and `>`, and `JSON.stringify` emits all three literally. The Go byte-twin
|
|
61
|
+
* hand-rolls the same serialization (`ApiRequestSigningInput`) precisely because
|
|
62
|
+
* `encoding/json` would emit `\u0026` / `\u003c` / `\u003e` instead and silently fork
|
|
63
|
+
* the signed bytes.
|
|
64
|
+
*
|
|
65
|
+
* PURE and clientless: import it in a signing backend and in a verifier alike.
|
|
66
|
+
*/
|
|
67
|
+
declare const apiRequestSigningInput: (payload: RequestProofPayload) => Uint8Array;
|
|
68
|
+
/**
|
|
69
|
+
* The `bodyHash` member: canonical unpadded base64url of the SHA-256 of the
|
|
70
|
+
* APPLICATION body octets — the bytes the sender handed its HTTP client, which a
|
|
71
|
+
* verifier obtains after reversing transfer encoding and content encoding. Zero
|
|
72
|
+
* octets hash to `EMPTY_BODY_SHA256`.
|
|
73
|
+
*/
|
|
74
|
+
declare const sha256BodyHash: (body: Uint8Array) => string;
|
|
75
|
+
interface SignApiRequestInput {
|
|
76
|
+
/** The HTTP method, uppercase. */
|
|
77
|
+
method: string;
|
|
78
|
+
/** The API's lowercase authority — `host` on 443, `host:port` otherwise. */
|
|
79
|
+
host: string;
|
|
80
|
+
/** The exact origin-form request target this proof will ride. */
|
|
81
|
+
path: string;
|
|
82
|
+
/** Application body octets; omitted or empty hashes to `EMPTY_BODY_SHA256`. */
|
|
83
|
+
body?: Uint8Array;
|
|
84
|
+
/** CID of the leaf credential presented alongside this proof. */
|
|
85
|
+
credentialCID: string;
|
|
86
|
+
/**
|
|
87
|
+
* The signing key's DID URL. Its DID portion MUST be the leaf credential's
|
|
88
|
+
* `aud` — that equality IS the possession being proven.
|
|
89
|
+
*/
|
|
90
|
+
kid: string;
|
|
91
|
+
/** Raw Ed25519 signer over the JWS signing input. */
|
|
92
|
+
sign: (message: Uint8Array) => Promise<Uint8Array>;
|
|
93
|
+
/** Issued-at override — unix seconds. Default `Math.floor(Date.now() / 1000)`. */
|
|
94
|
+
iat?: number;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Sign one request. The producer half of the byte contract.
|
|
98
|
+
*
|
|
99
|
+
* `createJws` serializes the payload with `JSON.stringify`, so passing the
|
|
100
|
+
* fixed-order object makes the emitted payload segment EXACTLY
|
|
101
|
+
* `apiRequestSigningInput(payload)` — the equivalence is pinned by a test rather
|
|
102
|
+
* than assumed, because it is the whole reason there is one byte contract and
|
|
103
|
+
* not two.
|
|
104
|
+
*/
|
|
105
|
+
declare const signApiRequest: (input: SignApiRequestInput) => Promise<{
|
|
106
|
+
proof: string;
|
|
107
|
+
payload: RequestProofPayload;
|
|
108
|
+
}>;
|
|
109
|
+
/**
|
|
110
|
+
* The two headers a credential-gated request carries. The `Authorization` scheme
|
|
111
|
+
* is the token `DFOS`, deliberately NOT `Bearer`: nothing carried here is a
|
|
112
|
+
* bearer token, and naming it one invites bearer handling (logging, caching,
|
|
113
|
+
* forwarding) that this artifact exists to make useless.
|
|
114
|
+
*/
|
|
115
|
+
declare const buildApiAuthHeaders: (input: {
|
|
116
|
+
proof: string;
|
|
117
|
+
credential: string;
|
|
118
|
+
}) => {
|
|
119
|
+
Authorization: string;
|
|
120
|
+
"X-Credential": string;
|
|
121
|
+
};
|
|
122
|
+
/**
|
|
123
|
+
* The verdict class. Branch on `reason`, never on message text.
|
|
124
|
+
*
|
|
125
|
+
* - `invalid` — checked and failed.
|
|
126
|
+
* - `unverifiable` — could not check (an unresolvable presenter, an unreachable
|
|
127
|
+
* revocation source). A transient resolution failure is the server's
|
|
128
|
+
* condition, not the caller's.
|
|
129
|
+
* - `config` — the DEPLOYMENT is misconfigured (a `W + S` over the 300-second
|
|
130
|
+
* ceiling, or an empty required action). Not a judgment about the artifact.
|
|
131
|
+
*/
|
|
132
|
+
type RequestProofFailureReason = 'invalid' | 'unverifiable' | 'config';
|
|
133
|
+
/**
|
|
134
|
+
* The verification phase a failure arose in. Load-bearing for HTTP mapping: an
|
|
135
|
+
* `invalid` proof-layer failure is a 401 (with a `WWW-Authenticate: DFOS`
|
|
136
|
+
* challenge), an `invalid` credential-layer failure is a 403. `status` carries
|
|
137
|
+
* the recommended code directly so middleware never has to re-derive it.
|
|
138
|
+
*/
|
|
139
|
+
type RequestProofFailurePhase = 'proof' | 'credential' | 'config';
|
|
140
|
+
/** Branch on `reason`/`phase`/`status`, never on message text. */
|
|
141
|
+
declare class ApiRequestVerifyError extends Error {
|
|
142
|
+
readonly reason: RequestProofFailureReason;
|
|
143
|
+
readonly phase: RequestProofFailurePhase;
|
|
144
|
+
/** Recommended HTTP status: 401 proof-invalid, 403 credential-invalid, 503 unverifiable, 500 config. */
|
|
145
|
+
readonly status: number;
|
|
146
|
+
constructor(reason: RequestProofFailureReason, phase: RequestProofFailurePhase, status: number, message: string);
|
|
147
|
+
}
|
|
148
|
+
interface VerifyApiRequestInput {
|
|
149
|
+
/** The request-proof JWS — the `Authorization: DFOS <token>` token, scheme stripped. */
|
|
150
|
+
proof: string;
|
|
151
|
+
/** The leaf credential JWS — the `X-Credential` value. It embeds its chain in `prf`. */
|
|
152
|
+
credential: string;
|
|
153
|
+
/**
|
|
154
|
+
* THE VERIFIER'S OWN CONFIGURED AUTHORITY for the route being served — a value
|
|
155
|
+
* the deployment holds, NEVER one read from the request. `Host`,
|
|
156
|
+
* `X-Forwarded-Host`, and the request URL's authority are all attacker-supplied:
|
|
157
|
+
* a verifier that compared the proof's `host` against a request header would
|
|
158
|
+
* have no host binding at all. Include the port when it is not 443.
|
|
159
|
+
*
|
|
160
|
+
* It is also the id half of the `api:<host>` resource string this verifier
|
|
161
|
+
* requires, so the request binding and the grant name the same origin.
|
|
162
|
+
*/
|
|
163
|
+
host: string;
|
|
164
|
+
/** The received request's method. */
|
|
165
|
+
method: string;
|
|
166
|
+
/** The received origin-form request target — path plus query string, byte for byte. */
|
|
167
|
+
path: string;
|
|
168
|
+
/** The received application body octets, post-content-decoding. Omitted = no body. */
|
|
169
|
+
body?: Uint8Array;
|
|
170
|
+
/**
|
|
171
|
+
* Cap on the decoded body this verifier will hash, in bytes. Default
|
|
172
|
+
* `MAX_BODY_BYTES`. A body over the cap is refused BEFORE the SHA-256 (a
|
|
173
|
+
* proof-layer `413`), so a well-formed proof with a bad signature cannot force
|
|
174
|
+
* an unbounded hash. NOTE: the spec's "abort decode at the cap" is a MIDDLEWARE
|
|
175
|
+
* obligation — by the time the body reaches this helper it is already a buffered
|
|
176
|
+
* `Uint8Array`, so this is the second, defensive cap; the middleware must still
|
|
177
|
+
* bound decoding upstream (a decompression bomb inflates before the kit sees it).
|
|
178
|
+
*/
|
|
179
|
+
maxBodyBytes?: number;
|
|
180
|
+
/** The action token this route requires. Default `read:profile`. */
|
|
181
|
+
action?: string;
|
|
182
|
+
/** Acceptance window `W`, seconds. Default 60. `W + S` MUST NOT exceed 300. */
|
|
183
|
+
windowSeconds?: number;
|
|
184
|
+
/** Clock-skew allowance `S`, seconds. Default 60. `W + S` MUST NOT exceed 300. */
|
|
185
|
+
skewSeconds?: number;
|
|
186
|
+
/**
|
|
187
|
+
* Accept a presenter resolution whose tip could not be verified (cache-only or
|
|
188
|
+
* empty-delta-against-cache). Default FALSE: key resolution is CURRENT-STATE,
|
|
189
|
+
* and a rotated-out key must not keep minting proofs against a stale cache.
|
|
190
|
+
*/
|
|
191
|
+
allowStale?: boolean;
|
|
192
|
+
/** Clock injection (unix ms). Default `Date.now()`. */
|
|
193
|
+
now?: () => number;
|
|
194
|
+
}
|
|
195
|
+
interface VerifiedRequestProof {
|
|
196
|
+
/** The chain's root `iss` — the DID whose data this request serves. */
|
|
197
|
+
subjectDID: string;
|
|
198
|
+
/** The authority the grant and the binding both name. */
|
|
199
|
+
host: string;
|
|
200
|
+
/** The action token the leaf's attenuation was found to cover. */
|
|
201
|
+
action: string;
|
|
202
|
+
/** The proof's issued-at, unix seconds. */
|
|
203
|
+
iat: number;
|
|
204
|
+
/** The leaf credential's CID, re-derived and equal to the proof's member. */
|
|
205
|
+
credentialCID: string;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Verify a credential-gated request — API-AUTH.md's eleven steps, in an order
|
|
209
|
+
* that honors both load-bearing ordering rules: the proof signature gates every
|
|
210
|
+
* credential-chain step, and body hashing runs after the cheaper binding checks.
|
|
211
|
+
*
|
|
212
|
+
* `client` supplies the resolver seam (current-state identity resolution plus the
|
|
213
|
+
* revocation checker) exactly as `verifySiwd` does. Everything the verifier
|
|
214
|
+
* compares against — host, method, path, body, action — is passed in BY THE
|
|
215
|
+
* DEPLOYMENT: this helper never reads a request object, because the one thing a
|
|
216
|
+
* host binding must not be sourced from is the request.
|
|
217
|
+
*
|
|
218
|
+
* Throws `ApiRequestVerifyError`; branch on `reason`/`phase`/`status`, never on
|
|
219
|
+
* message text. `status` is the recommended HTTP code (401 proof-invalid, 403
|
|
220
|
+
* credential-invalid, 503 unverifiable, 500 config).
|
|
221
|
+
*
|
|
222
|
+
* REVOCATION AND RESOLUTION AVAILABILITY — read before deploying. This helper
|
|
223
|
+
* rejects a credential it KNOWS is revoked (`isRevoked` true at any chain level).
|
|
224
|
+
* It does NOT, with the default client, fail closed when the revocation source is
|
|
225
|
+
* unreachable: the stock `createRevocationChecker` is fail-open by design
|
|
226
|
+
* ("no revocation found" and "could not reach any relay" both return false), the
|
|
227
|
+
* system-wide v1 stance that "non-revocation is never provable." Likewise a
|
|
228
|
+
* credential-issuer that is unresolvable because relays are down surfaces from the
|
|
229
|
+
* protocol verifier as a `CredentialVerificationError` and is reported here as
|
|
230
|
+
* `invalid` (403), not `unverifiable` (503) — the underlying callback cannot
|
|
231
|
+
* distinguish "genuinely absent" from "transiently unreachable." The PRESENTER
|
|
232
|
+
* side is availability-aware (a resolution failure or unverified/stale tip is
|
|
233
|
+
* `unverifiable`, failing closed unless `allowStale`); the CREDENTIAL side inherits
|
|
234
|
+
* the v1 primitives' limitation. A deployment that needs fail-closed-on-outage for
|
|
235
|
+
* the credential/revocation phase MUST inject an availability-aware `isRevoked`
|
|
236
|
+
* (one that THROWS when it reaches zero sources — the throw is surfaced here as
|
|
237
|
+
* `unverifiable`) via the client config. Tightening the default is a client-level
|
|
238
|
+
* change to the shared revocation/resolution contract (it governs SIWD and relay
|
|
239
|
+
* verification too), tracked outside this kit.
|
|
240
|
+
*/
|
|
241
|
+
declare const verifyApiRequest: (client: Client, input: VerifyApiRequestInput) => Promise<VerifiedRequestProof>;
|
|
242
|
+
|
|
243
|
+
export { ApiRequestVerifyError, DEFAULT_API_ACTION, DEFAULT_PROOF_SKEW_SECONDS, DEFAULT_PROOF_WINDOW_SECONDS, EMPTY_BODY_SHA256, MAX_BODY_BYTES, MAX_PROOF_FRESHNESS_SPAN_SECONDS, MAX_REQUEST_PROOF_SIZE, REQUEST_PROOF_JWS_TYP, type RequestProofFailurePhase, type RequestProofFailureReason, type RequestProofPayload, type SignApiRequestInput, type VerifiedRequestProof, type VerifyApiRequestInput, apiRequestSigningInput, buildApiAuthHeaders, sha256BodyHash, signApiRequest, verifyApiRequest };
|
package/dist/api-auth.js
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
// src/api-auth.ts
|
|
2
|
+
import { decodeMultikey } from "@metalabel/dfos-protocol/chain";
|
|
3
|
+
import {
|
|
4
|
+
CredentialVerificationError,
|
|
5
|
+
decodeDFOSCredentialUnsafe,
|
|
6
|
+
matchesResource,
|
|
7
|
+
MAX_CREDENTIAL_SIZE,
|
|
8
|
+
verifyDelegationChain,
|
|
9
|
+
verifyDFOSCredential
|
|
10
|
+
} from "@metalabel/dfos-protocol/credentials";
|
|
11
|
+
import {
|
|
12
|
+
assertJwsProfile,
|
|
13
|
+
base64urlDecode,
|
|
14
|
+
base64urlEncode,
|
|
15
|
+
createJws,
|
|
16
|
+
decodeJwsUnsafe,
|
|
17
|
+
sha256,
|
|
18
|
+
verifyJws
|
|
19
|
+
} from "@metalabel/dfos-protocol/crypto";
|
|
20
|
+
var REQUEST_PROOF_JWS_TYP = "did:dfos:request-proof";
|
|
21
|
+
var EMPTY_BODY_SHA256 = "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU";
|
|
22
|
+
var MAX_REQUEST_PROOF_SIZE = 4096;
|
|
23
|
+
var DEFAULT_PROOF_WINDOW_SECONDS = 60;
|
|
24
|
+
var DEFAULT_PROOF_SKEW_SECONDS = 60;
|
|
25
|
+
var MAX_PROOF_FRESHNESS_SPAN_SECONDS = 300;
|
|
26
|
+
var DEFAULT_API_ACTION = "read:profile";
|
|
27
|
+
var MAX_BODY_BYTES = 1048576;
|
|
28
|
+
var MAX_DELEGATION_DEPTH = 16;
|
|
29
|
+
var encoder = new TextEncoder();
|
|
30
|
+
var EMPTY_BODY = new Uint8Array(0);
|
|
31
|
+
var UPPERCASE_METHOD = /^[A-Z0-9!#$%&'*+.^_`|~-]+$/;
|
|
32
|
+
var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
33
|
+
var CTL_OR_SPACE = /[\u0000-\u0020\u007f]/;
|
|
34
|
+
var BASE64URL_32 = /^[A-Za-z0-9_-]{43}$/;
|
|
35
|
+
var assertNoLoneSurrogate = (value, field) => {
|
|
36
|
+
if (LONE_SURROGATE.test(value)) {
|
|
37
|
+
throw new Error(`invalid request proof: ${field} must be well-formed Unicode`);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
var validateRequestProofPayload = (value) => {
|
|
41
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
42
|
+
throw new Error("invalid request proof: expected a JSON object");
|
|
43
|
+
}
|
|
44
|
+
const raw = value;
|
|
45
|
+
for (const field of ["method", "host", "path", "bodyHash", "credentialCID"]) {
|
|
46
|
+
if (typeof raw[field] !== "string" || raw[field] === "") {
|
|
47
|
+
throw new Error(`invalid request proof: ${field} must be a non-empty string`);
|
|
48
|
+
}
|
|
49
|
+
assertNoLoneSurrogate(raw[field], field);
|
|
50
|
+
}
|
|
51
|
+
const method = raw["method"];
|
|
52
|
+
if (!UPPERCASE_METHOD.test(method)) {
|
|
53
|
+
throw new Error("invalid request proof: method must be an uppercase HTTP method token");
|
|
54
|
+
}
|
|
55
|
+
const host = raw["host"];
|
|
56
|
+
if (host !== host.toLowerCase() || /[\s/\\?#]/.test(host)) {
|
|
57
|
+
throw new Error("invalid request proof: host must be a lowercase authority, without a scheme");
|
|
58
|
+
}
|
|
59
|
+
const path = raw["path"];
|
|
60
|
+
if (!path.startsWith("/")) {
|
|
61
|
+
throw new Error("invalid request proof: path must begin with /");
|
|
62
|
+
}
|
|
63
|
+
if (path.includes("#")) {
|
|
64
|
+
throw new Error("invalid request proof: path must not carry a fragment");
|
|
65
|
+
}
|
|
66
|
+
if (CTL_OR_SPACE.test(path)) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
"invalid request proof: path must not contain whitespace or control characters"
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
const bodyHash = raw["bodyHash"];
|
|
72
|
+
if (!BASE64URL_32.test(bodyHash) || base64urlEncode(base64urlDecode(bodyHash)) !== bodyHash) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
"invalid request proof: bodyHash must be the canonical unpadded base64url of 32 bytes"
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
const iat = raw["iat"];
|
|
78
|
+
if (typeof iat !== "number" || !Number.isSafeInteger(iat) || iat <= 0) {
|
|
79
|
+
throw new Error("invalid request proof: iat must be a positive integer");
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
method,
|
|
83
|
+
host,
|
|
84
|
+
path,
|
|
85
|
+
bodyHash,
|
|
86
|
+
credentialCID: raw["credentialCID"],
|
|
87
|
+
iat
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
var apiRequestSigningInput = (payload) => {
|
|
91
|
+
const parsed = validateRequestProofPayload(payload);
|
|
92
|
+
return encoder.encode(
|
|
93
|
+
JSON.stringify({
|
|
94
|
+
method: parsed.method,
|
|
95
|
+
host: parsed.host,
|
|
96
|
+
path: parsed.path,
|
|
97
|
+
bodyHash: parsed.bodyHash,
|
|
98
|
+
credentialCID: parsed.credentialCID,
|
|
99
|
+
iat: parsed.iat
|
|
100
|
+
})
|
|
101
|
+
);
|
|
102
|
+
};
|
|
103
|
+
var sha256BodyHash = (body) => base64urlEncode(sha256(body));
|
|
104
|
+
var signApiRequest = async (input) => {
|
|
105
|
+
const payload = validateRequestProofPayload({
|
|
106
|
+
method: input.method,
|
|
107
|
+
host: input.host,
|
|
108
|
+
path: input.path,
|
|
109
|
+
bodyHash: sha256BodyHash(input.body ?? EMPTY_BODY),
|
|
110
|
+
credentialCID: input.credentialCID,
|
|
111
|
+
iat: input.iat ?? Math.floor(Date.now() / 1e3)
|
|
112
|
+
});
|
|
113
|
+
if (!input.kid.includes("#")) {
|
|
114
|
+
throw new Error("invalid request proof: kid must be a DID URL");
|
|
115
|
+
}
|
|
116
|
+
const proof = await createJws({
|
|
117
|
+
header: { alg: "EdDSA", typ: REQUEST_PROOF_JWS_TYP, kid: input.kid },
|
|
118
|
+
payload: {
|
|
119
|
+
method: payload.method,
|
|
120
|
+
host: payload.host,
|
|
121
|
+
path: payload.path,
|
|
122
|
+
bodyHash: payload.bodyHash,
|
|
123
|
+
credentialCID: payload.credentialCID,
|
|
124
|
+
iat: payload.iat
|
|
125
|
+
},
|
|
126
|
+
sign: input.sign
|
|
127
|
+
});
|
|
128
|
+
if (proof.length > MAX_REQUEST_PROOF_SIZE) {
|
|
129
|
+
throw new Error(`request proof exceeds max size: ${proof.length} > ${MAX_REQUEST_PROOF_SIZE}`);
|
|
130
|
+
}
|
|
131
|
+
return { proof, payload };
|
|
132
|
+
};
|
|
133
|
+
var buildApiAuthHeaders = (input) => ({
|
|
134
|
+
Authorization: `DFOS ${input.proof}`,
|
|
135
|
+
"X-Credential": input.credential
|
|
136
|
+
});
|
|
137
|
+
var ApiRequestVerifyError = class extends Error {
|
|
138
|
+
reason;
|
|
139
|
+
phase;
|
|
140
|
+
/** Recommended HTTP status: 401 proof-invalid, 403 credential-invalid, 503 unverifiable, 500 config. */
|
|
141
|
+
status;
|
|
142
|
+
constructor(reason, phase, status, message) {
|
|
143
|
+
super(message);
|
|
144
|
+
this.name = "ApiRequestVerifyError";
|
|
145
|
+
this.reason = reason;
|
|
146
|
+
this.phase = phase;
|
|
147
|
+
this.status = status;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
var invalidProof = (message) => new ApiRequestVerifyError("invalid", "proof", 401, message);
|
|
151
|
+
var invalidCredential = (message) => new ApiRequestVerifyError("invalid", "credential", 403, message);
|
|
152
|
+
var unverifiableProof = (message) => new ApiRequestVerifyError("unverifiable", "proof", 503, message);
|
|
153
|
+
var unverifiableCredential = (message) => new ApiRequestVerifyError("unverifiable", "credential", 503, message);
|
|
154
|
+
var misconfigured = (message) => new ApiRequestVerifyError("config", "config", 500, message);
|
|
155
|
+
var discoverChainRoot = (leafToken) => {
|
|
156
|
+
let token = leafToken;
|
|
157
|
+
for (let depth = 0; depth < MAX_DELEGATION_DEPTH; depth++) {
|
|
158
|
+
const decoded = decodeDFOSCredentialUnsafe(token);
|
|
159
|
+
if (!decoded) throw invalidCredential("failed to decode presented credential");
|
|
160
|
+
if (decoded.payload.prf.length === 0) return decoded.payload.iss;
|
|
161
|
+
if (decoded.payload.prf.length > 1) {
|
|
162
|
+
throw invalidCredential("delegation chain: multi-parent credentials are not supported");
|
|
163
|
+
}
|
|
164
|
+
token = decoded.payload.prf[0];
|
|
165
|
+
}
|
|
166
|
+
throw invalidCredential("delegation chain too deep (max 16 credentials)");
|
|
167
|
+
};
|
|
168
|
+
var verifyApiRequest = async (client, input) => {
|
|
169
|
+
const window = input.windowSeconds ?? DEFAULT_PROOF_WINDOW_SECONDS;
|
|
170
|
+
const skew = input.skewSeconds ?? DEFAULT_PROOF_SKEW_SECONDS;
|
|
171
|
+
for (const [name, value] of [
|
|
172
|
+
["windowSeconds", window],
|
|
173
|
+
["skewSeconds", skew]
|
|
174
|
+
]) {
|
|
175
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
176
|
+
throw misconfigured(`${name} must be a non-negative integer`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (window + skew > MAX_PROOF_FRESHNESS_SPAN_SECONDS) {
|
|
180
|
+
throw misconfigured(
|
|
181
|
+
`request proof freshness span W + S exceeds ${MAX_PROOF_FRESHNESS_SPAN_SECONDS} seconds: ${window} + ${skew}`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
const action = input.action ?? DEFAULT_API_ACTION;
|
|
185
|
+
if (action.split(",").every((token) => token.trim() === "")) {
|
|
186
|
+
throw misconfigured("required action must name a non-empty token");
|
|
187
|
+
}
|
|
188
|
+
const maxBodyBytes = input.maxBodyBytes ?? MAX_BODY_BYTES;
|
|
189
|
+
if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 0) {
|
|
190
|
+
throw misconfigured("maxBodyBytes must be a non-negative integer");
|
|
191
|
+
}
|
|
192
|
+
if (input.proof.length > MAX_REQUEST_PROOF_SIZE) {
|
|
193
|
+
throw invalidProof(
|
|
194
|
+
`request proof exceeds max size: ${input.proof.length} > ${MAX_REQUEST_PROOF_SIZE}`
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
if (input.credential.length > MAX_CREDENTIAL_SIZE) {
|
|
198
|
+
throw invalidProof(
|
|
199
|
+
`credential exceeds max size: ${input.credential.length} > ${MAX_CREDENTIAL_SIZE}`
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
const decoded = decodeJwsUnsafe(input.proof);
|
|
203
|
+
if (!decoded) throw invalidProof("failed to decode request proof JWS");
|
|
204
|
+
const rawHeader = decoded.header;
|
|
205
|
+
if (typeof rawHeader !== "object" || rawHeader === null || Array.isArray(rawHeader)) {
|
|
206
|
+
throw invalidProof("request proof protected header must be an object");
|
|
207
|
+
}
|
|
208
|
+
assertJwsProfile(rawHeader, invalidProof);
|
|
209
|
+
if (decoded.header.typ !== REQUEST_PROOF_JWS_TYP) {
|
|
210
|
+
throw invalidProof(`invalid typ: expected ${REQUEST_PROOF_JWS_TYP}, got ${decoded.header.typ}`);
|
|
211
|
+
}
|
|
212
|
+
const kid = decoded.header.kid;
|
|
213
|
+
if (typeof kid !== "string" || !kid.includes("#")) {
|
|
214
|
+
throw invalidProof("request proof kid must be a DID URL");
|
|
215
|
+
}
|
|
216
|
+
const presenterDID = kid.substring(0, kid.indexOf("#"));
|
|
217
|
+
const presenterKeyId = kid.substring(kid.indexOf("#") + 1);
|
|
218
|
+
const payloadSegment = input.proof.split(".")[1];
|
|
219
|
+
if (payloadSegment === void 0) throw invalidProof("failed to decode request proof payload");
|
|
220
|
+
let payload;
|
|
221
|
+
try {
|
|
222
|
+
const source = new TextDecoder("utf-8", { fatal: true }).decode(
|
|
223
|
+
base64urlDecode(payloadSegment)
|
|
224
|
+
);
|
|
225
|
+
payload = validateRequestProofPayload(JSON.parse(source));
|
|
226
|
+
} catch (err) {
|
|
227
|
+
throw invalidProof(err instanceof Error ? err.message : "invalid request proof payload");
|
|
228
|
+
}
|
|
229
|
+
const now = Math.floor((input.now ? input.now() : Date.now()) / 1e3);
|
|
230
|
+
if (now - payload.iat > window) throw invalidProof("request proof is stale");
|
|
231
|
+
if (payload.iat - now > skew) {
|
|
232
|
+
throw invalidProof("request proof iat is beyond the clock-skew allowance");
|
|
233
|
+
}
|
|
234
|
+
if (payload.method !== input.method) throw invalidProof("request proof method mismatch");
|
|
235
|
+
if (payload.host !== input.host) throw invalidProof("request proof host mismatch");
|
|
236
|
+
if (payload.path !== input.path) throw invalidProof("request proof path mismatch");
|
|
237
|
+
const body = input.body ?? EMPTY_BODY;
|
|
238
|
+
if (body.length > maxBodyBytes) {
|
|
239
|
+
throw new ApiRequestVerifyError(
|
|
240
|
+
"invalid",
|
|
241
|
+
"proof",
|
|
242
|
+
413,
|
|
243
|
+
`request body exceeds max size: ${body.length} > ${maxBodyBytes}`
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
if (payload.bodyHash !== sha256BodyHash(body)) {
|
|
247
|
+
throw invalidProof("request proof bodyHash mismatch");
|
|
248
|
+
}
|
|
249
|
+
let resolved;
|
|
250
|
+
try {
|
|
251
|
+
resolved = await client.identity(presenterDID);
|
|
252
|
+
} catch (err) {
|
|
253
|
+
throw unverifiableProof(
|
|
254
|
+
`failed to resolve request proof presenter: ${err instanceof Error ? err.message : String(err)}`
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
const axes = resolved.trust.unverifiable ?? [];
|
|
258
|
+
if (!input.allowStale && (axes.includes("tip") || resolved.provenance.fromCache)) {
|
|
259
|
+
throw unverifiableProof(
|
|
260
|
+
"presenter identity resolution is stale (tip unverified) \u2014 refusing to authenticate against a cached identity state; pass allowStale: true to accept the risk"
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
const state = resolved.value;
|
|
264
|
+
if (state.isDeleted) throw invalidProof("request proof presenter identity is deleted");
|
|
265
|
+
const key = [...state.authKeys, ...state.assertKeys, ...state.controllerKeys].find(
|
|
266
|
+
(candidate) => candidate.id === presenterKeyId
|
|
267
|
+
);
|
|
268
|
+
if (!key) throw invalidProof("request proof signing key is not a current key of the presenter");
|
|
269
|
+
try {
|
|
270
|
+
verifyJws({ token: input.proof, publicKey: decodeMultikey(key.publicKeyMultibase).keyBytes });
|
|
271
|
+
} catch (err) {
|
|
272
|
+
throw invalidProof(err instanceof Error ? err.message : "invalid request proof signature");
|
|
273
|
+
}
|
|
274
|
+
const { isRevoked, resolveIdentity } = client.callbacks();
|
|
275
|
+
const rootDID = discoverChainRoot(input.credential);
|
|
276
|
+
let leaf;
|
|
277
|
+
let chain;
|
|
278
|
+
try {
|
|
279
|
+
leaf = await verifyDFOSCredential(input.credential, { resolveIdentity, now });
|
|
280
|
+
if (await isRevoked(leaf.iss, leaf.credentialCID)) {
|
|
281
|
+
throw new CredentialVerificationError("credential is revoked");
|
|
282
|
+
}
|
|
283
|
+
const verifiedChain = await verifyDelegationChain(leaf, {
|
|
284
|
+
resolveIdentity,
|
|
285
|
+
rootDID,
|
|
286
|
+
now,
|
|
287
|
+
isRevoked
|
|
288
|
+
});
|
|
289
|
+
chain = verifiedChain.chain;
|
|
290
|
+
} catch (err) {
|
|
291
|
+
if (err instanceof ApiRequestVerifyError) throw err;
|
|
292
|
+
if (err instanceof CredentialVerificationError) throw invalidCredential(err.message);
|
|
293
|
+
throw unverifiableCredential(
|
|
294
|
+
`credential verification could not complete: ${err instanceof Error ? err.message : String(err)}`
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
if (leaf.credentialCID !== payload.credentialCID) {
|
|
298
|
+
throw invalidCredential("request proof credentialCID does not match the presented credential");
|
|
299
|
+
}
|
|
300
|
+
for (const hop of chain) {
|
|
301
|
+
if (hop.aud === "*") {
|
|
302
|
+
throw invalidCredential(
|
|
303
|
+
'a credential in the presented chain carries a public audience (aud: "*")'
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (leaf.aud !== presenterDID) {
|
|
308
|
+
throw invalidCredential("credential audience does not match the request proof signing key");
|
|
309
|
+
}
|
|
310
|
+
if (!await matchesResource(leaf.att, `api:${input.host}`, action)) {
|
|
311
|
+
throw invalidCredential(`credential does not cover ${action} on api:${input.host}`);
|
|
312
|
+
}
|
|
313
|
+
return {
|
|
314
|
+
subjectDID: rootDID,
|
|
315
|
+
host: input.host,
|
|
316
|
+
action,
|
|
317
|
+
iat: payload.iat,
|
|
318
|
+
credentialCID: leaf.credentialCID
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
export {
|
|
322
|
+
ApiRequestVerifyError,
|
|
323
|
+
DEFAULT_API_ACTION,
|
|
324
|
+
DEFAULT_PROOF_SKEW_SECONDS,
|
|
325
|
+
DEFAULT_PROOF_WINDOW_SECONDS,
|
|
326
|
+
EMPTY_BODY_SHA256,
|
|
327
|
+
MAX_BODY_BYTES,
|
|
328
|
+
MAX_PROOF_FRESHNESS_SPAN_SECONDS,
|
|
329
|
+
MAX_REQUEST_PROOF_SIZE,
|
|
330
|
+
REQUEST_PROOF_JWS_TYP,
|
|
331
|
+
apiRequestSigningInput,
|
|
332
|
+
buildApiAuthHeaders,
|
|
333
|
+
sha256BodyHash,
|
|
334
|
+
signApiRequest,
|
|
335
|
+
verifyApiRequest
|
|
336
|
+
};
|
package/dist/siwd.d.ts
CHANGED
|
@@ -103,7 +103,10 @@ interface SiwdLoginRequest {
|
|
|
103
103
|
* a `domain` or `did` that drifts between mint and verify is a check that
|
|
104
104
|
* silently stops checking.
|
|
105
105
|
*
|
|
106
|
-
* SINGLE USE: consume the nonce on the way back, pass or fail.
|
|
106
|
+
* SINGLE USE: consume the nonce on the way back, pass or fail. A backend
|
|
107
|
+
* holding its minted nonces in shared state should hand `verifySiwd` a
|
|
108
|
+
* `consumeNonce` instead of this object's `nonce`, so the consumption is
|
|
109
|
+
* atomic and is the last thing that happens before a session is granted.
|
|
107
110
|
*
|
|
108
111
|
* WHOEVER VERIFIES MUST HAVE MINTED. A verifier that accepts an expectation
|
|
109
112
|
* supplied by the party presenting the JWS is comparing a value against
|
|
@@ -111,8 +114,14 @@ interface SiwdLoginRequest {
|
|
|
111
114
|
* expectation comes from the verifier's own prior state (this object, held
|
|
112
115
|
* server-side or in the session that began the sign-in) or from an
|
|
113
116
|
* independent validation of it.
|
|
117
|
+
*
|
|
118
|
+
* `nonce` is REQUIRED here even though `SiwdExpectations` leaves it optional
|
|
119
|
+
* for the `consumeNonce` form: what this function mints into the challenge is
|
|
120
|
+
* always a string, and an RP persisting this object must get it back.
|
|
114
121
|
*/
|
|
115
|
-
expect: Pick<SiwdExpectations, 'domain' | '
|
|
122
|
+
expect: Pick<SiwdExpectations, 'domain' | 'did'> & {
|
|
123
|
+
nonce: string;
|
|
124
|
+
};
|
|
116
125
|
/** base64url canonical challenge bytes, exactly as embedded in `url`. */
|
|
117
126
|
challenge: string;
|
|
118
127
|
/** ISO whole-second mint timestamp, exactly as embedded in the signed bytes. */
|
|
@@ -131,15 +140,22 @@ interface SiwdLoginRequest {
|
|
|
131
140
|
* not downgraded, so the param is dropped here instead of being forwarded into
|
|
132
141
|
* a guaranteed refusal.
|
|
133
142
|
*
|
|
143
|
+
* The same judgment BOUNDS THE SCOPE. Every scope past `identity` returns a
|
|
144
|
+
* credential issued to a `client_did` — the one param a loopback request cannot
|
|
145
|
+
* carry — so specs/SIWD.md admits a loopback target for `scope=identity` only.
|
|
146
|
+
* Asking for more from a local port is not a downgrade the way `client_did` is;
|
|
147
|
+
* there is nothing to drop, so it throws.
|
|
148
|
+
*
|
|
134
149
|
* It also owns the WIRE PARAM NAMES (`challenge`, `redirect_uri`, `scope`,
|
|
135
150
|
* `client_did`) as their single source in this package. They are snake_case on
|
|
136
151
|
* the wire and camelCase everywhere else, which is exactly the kind of seam
|
|
137
152
|
* every hand-rolled RP re-implements and eventually gets wrong.
|
|
138
153
|
*
|
|
139
154
|
* PURE: no DOM, no storage, no navigation, no fetch — identical in a browser
|
|
140
|
-
* and in Node. Throws on an unparseable `authorizeUrl` or `redirectUri`,
|
|
141
|
-
*
|
|
142
|
-
*
|
|
155
|
+
* and in Node. Throws on an unparseable `authorizeUrl` or `redirectUri`, and on
|
|
156
|
+
* a non-`identity` scope over a loopback redirect, because those are mistakes
|
|
157
|
+
* in the RP's own configuration rather than runtime conditions a result type
|
|
158
|
+
* would help a caller recover from.
|
|
143
159
|
*/
|
|
144
160
|
declare const createSiwdLoginRequest: (input: SiwdLoginRequestInput) => SiwdLoginRequest;
|
|
145
161
|
/**
|
|
@@ -214,8 +230,26 @@ declare const validateSiwdSignRequest: (jwsToken: string, options: ValidateSiwdS
|
|
|
214
230
|
interface SiwdExpectations {
|
|
215
231
|
/** The verifier's own origin — MUST match the challenge domain. */
|
|
216
232
|
domain: string;
|
|
217
|
-
/**
|
|
218
|
-
|
|
233
|
+
/**
|
|
234
|
+
* The nonce this verifier issued for the session. Supply EXACTLY ONE of
|
|
235
|
+
* `nonce` and `consumeNonce`.
|
|
236
|
+
*/
|
|
237
|
+
nonce?: string;
|
|
238
|
+
/**
|
|
239
|
+
* Atomically consume the presented nonce against verifier-minted state — a
|
|
240
|
+
* Redis `GETDEL`, a `DELETE … RETURNING` row — returning true iff THIS
|
|
241
|
+
* verifier minted it and it was unspent. Membership in the verifier's own
|
|
242
|
+
* minted state is what proves the verifier minted it, which is the whole
|
|
243
|
+
* check; an equality test against a `nonce` fed in from the presented
|
|
244
|
+
* artifact is a value compared against itself. The ATOMICITY is yours: a
|
|
245
|
+
* get-then-delete lets two concurrent replays both win.
|
|
246
|
+
*
|
|
247
|
+
* Called AT MOST ONCE, and only after every other check has passed —
|
|
248
|
+
* signature, current-key resolution, did binding, domain, timestamp — so an
|
|
249
|
+
* otherwise-invalid presentation can never burn a live nonce, and the
|
|
250
|
+
* consumption is the last gate before the caller grants anything.
|
|
251
|
+
*/
|
|
252
|
+
consumeNonce?: (nonce: string) => boolean | Promise<boolean>;
|
|
219
253
|
/** If set, the challenge (and identity) MUST bind to this DID. */
|
|
220
254
|
did?: string;
|
|
221
255
|
/** If set, the signed challenge's timestamp MUST equal this exact value. */
|
package/dist/siwd.js
CHANGED
|
@@ -124,6 +124,10 @@ var parseUrlOrThrow = (value, field) => {
|
|
|
124
124
|
var createSiwdLoginRequest = (input) => {
|
|
125
125
|
const authorizeUrl = parseUrlOrThrow(input.authorizeUrl, "authorizeUrl");
|
|
126
126
|
const redirect = parseUrlOrThrow(input.redirectUri, "redirectUri");
|
|
127
|
+
const isLoopback = SIWD_LOOPBACK_HOSTS.has(bareHostname(redirect));
|
|
128
|
+
if (isLoopback && input.scope !== "identity") {
|
|
129
|
+
throw new Error("invalid SIWD login request: loopback redirects support scope=identity only");
|
|
130
|
+
}
|
|
127
131
|
const { challenge, encoded, nonce } = createSiwdChallenge({
|
|
128
132
|
domain: input.domain,
|
|
129
133
|
...input.statement !== void 0 ? { statement: input.statement } : {},
|
|
@@ -134,7 +138,7 @@ var createSiwdLoginRequest = (input) => {
|
|
|
134
138
|
url.searchParams.set("challenge", encoded);
|
|
135
139
|
url.searchParams.set("redirect_uri", input.redirectUri);
|
|
136
140
|
url.searchParams.set("scope", input.scope);
|
|
137
|
-
if (input.clientDid !== void 0 && !
|
|
141
|
+
if (input.clientDid !== void 0 && !isLoopback) {
|
|
138
142
|
url.searchParams.set("client_did", input.clientDid);
|
|
139
143
|
}
|
|
140
144
|
return {
|
|
@@ -233,6 +237,9 @@ var validateSiwdSignRequest = async (jwsToken, options) => {
|
|
|
233
237
|
var fail = (error) => ({ ok: false, error });
|
|
234
238
|
var verifySiwd = async (client, jws, expect) => {
|
|
235
239
|
try {
|
|
240
|
+
if (expect.nonce === void 0 === (expect.consumeNonce === void 0)) {
|
|
241
|
+
return fail("provide exactly one of nonce or consumeNonce");
|
|
242
|
+
}
|
|
236
243
|
const decoded = decodeJwsUnsafe(jws);
|
|
237
244
|
if (!decoded) return fail("failed to decode JWS");
|
|
238
245
|
const rawHeader = decoded.header;
|
|
@@ -275,7 +282,6 @@ var verifySiwd = async (client, jws, expect) => {
|
|
|
275
282
|
} catch (err) {
|
|
276
283
|
return fail(err instanceof Error ? err.message : "invalid signature");
|
|
277
284
|
}
|
|
278
|
-
if (payload.nonce !== expect.nonce) return fail("nonce mismatch");
|
|
279
285
|
if (payload.domain !== expect.domain) return fail("domain mismatch");
|
|
280
286
|
if (expect.timestamp !== void 0 && payload.timestamp !== expect.timestamp) {
|
|
281
287
|
return fail("timestamp does not match expected challenge timestamp");
|
|
@@ -288,6 +294,13 @@ var verifySiwd = async (client, jws, expect) => {
|
|
|
288
294
|
if (issuedMs - nowMs > MAX_CLOCK_SKEW_SECONDS * 1e3) {
|
|
289
295
|
return fail("challenge timestamp is in the future");
|
|
290
296
|
}
|
|
297
|
+
if (expect.consumeNonce !== void 0) {
|
|
298
|
+
if (!await expect.consumeNonce(payload.nonce)) {
|
|
299
|
+
return fail("nonce already used or not recognized");
|
|
300
|
+
}
|
|
301
|
+
} else if (payload.nonce !== expect.nonce) {
|
|
302
|
+
return fail("nonce mismatch");
|
|
303
|
+
}
|
|
291
304
|
const session = {
|
|
292
305
|
did,
|
|
293
306
|
domain: payload.domain,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metalabel/dfos-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "DFOS Client — read-only resolve + verify orchestration over untrusted relays. Fetch, resolve, verify-orchestration, cache; all crypto truth comes from @metalabel/dfos-protocol",
|
|
6
6
|
"license": "MIT",
|
|
@@ -27,6 +27,10 @@
|
|
|
27
27
|
"import": "./dist/index.js",
|
|
28
28
|
"types": "./dist/index.d.ts"
|
|
29
29
|
},
|
|
30
|
+
"./api-auth": {
|
|
31
|
+
"import": "./dist/api-auth.js",
|
|
32
|
+
"types": "./dist/api-auth.d.ts"
|
|
33
|
+
},
|
|
30
34
|
"./siwd": {
|
|
31
35
|
"import": "./dist/siwd.js",
|
|
32
36
|
"types": "./dist/siwd.d.ts"
|
|
@@ -43,15 +47,15 @@
|
|
|
43
47
|
"README.md"
|
|
44
48
|
],
|
|
45
49
|
"peerDependencies": {
|
|
46
|
-
"@metalabel/dfos-protocol": "^0.
|
|
47
|
-
"@metalabel/dfos-web-relay": "^0.
|
|
50
|
+
"@metalabel/dfos-protocol": "^0.32.0",
|
|
51
|
+
"@metalabel/dfos-web-relay": "^0.32.0"
|
|
48
52
|
},
|
|
49
53
|
"devDependencies": {
|
|
50
54
|
"@types/node": "^24.10.4",
|
|
51
55
|
"tsup": "^8.5.1",
|
|
52
56
|
"vitest": "^4.1.8",
|
|
53
|
-
"@metalabel/dfos-protocol": "0.
|
|
54
|
-
"@metalabel/dfos-web-relay": "0.
|
|
57
|
+
"@metalabel/dfos-protocol": "0.32.0",
|
|
58
|
+
"@metalabel/dfos-web-relay": "0.32.0"
|
|
55
59
|
},
|
|
56
60
|
"scripts": {
|
|
57
61
|
"build": "tsup",
|